Отсутствие псевдонима response-native-linear-gradient для response-native-web-linear-gradient для реагирования на собственное веб-приложение

У меня есть приложение, поддерживающее реакцию, с одним экраном, содержащим LinearGradient, который я пытаюсь заставить работать как веб-приложение.

Когда я запускаю приложение, у меня возникает следующая ошибка.

./node_modules/react-native-linear-gradient/common.js
C:/myapp/node_modules/react-native-linear-gradient/common.js:6
  3 | import type { ElementProps } from 'react';
  4 | import { requireNativeComponent, View } from 'react-native';
  5 | 
> 6 | export default requireNativeComponent('BVLinearGradient');
  7 | 
  8 | export type Point = $Exact<{x: number, y: number}>;
  9 | type LinearGradientProps = {

Без компонентов LinearGradient приложение работает нормально. Я считаю, что проблема в том, что react-native-linear-gradient не будет работать в веб-приложении.

Примечание: моя версия react-native-web - 0.13.14.

App.js

import React from 'react';
import LinearGradient from 'react-native-linear-gradient';
import { StyleSheet, Text } from 'react-native';

const styles = StyleSheet.create({
  drawer: {
    flex: 1,
  },
});

const GRADIENT_COLORS = ['blue', 'white', 'black'];

export default class App extends React.Component {
  
  render() {
    
    return (
      <LinearGradient
        colors={GRADIENT_COLORS}
        style={styles.drawer}
      >
        <Text>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vestibulum 
          erat in elit eleifend posuere. Cras interdum sagittis sem non consectetur. 
          Quisque nec faucibus odio. Phasellus ac ante felis. Nulla facilisis risus nulla, 
          eget interdum augue pellentesque id. Phasellus pellentesque augue eget porta 
          fringilla. Vivamus rhoncus scelerisque libero sit amet ullamcorper. Vestibulum 
          sit amet est ultrices, tristique risus vitae, aliquet ligula. Ut bibendum dignissim 
          tincidunt. In et tortor ullamcorper, dapibus arcu a, pellentesque velit. Praesent 
          ornare metus dapibus, tincidunt nulla in, maximus nisl. Ut molestie aliquam mi, 
          ac molestie purus sagittis eget. Aliquam sit amet lacus quis risus convallis semper.
        </Text>
      </LinearGradient>
    );
  }
}

Я видел, что для LinearLayout есть полифилл, то есть react-native-web-linear-gradient. Поэтому, насколько я понимаю, я просто устанавливаю этот пакет и присваиваю ему псевдоним исходного LinearLayout.

Я установил следующие

  • реагировать-родной-веб-линейный градиент: 1.1.1
  • Re-app-rewired: ^ 2.1.6,
  • настроить-cra: ^ 1.0.0,

Мой config-overrides.js:

const {addWebpackAlias} = require('customize-cra');

module.exports = function override(config, env) {
  config.module.rules.push(
    {
      test: /\.js$/,
      exclude: /node_modules\/(?!()\/).*/,
      use: {
        loader: 'babel-loader',
        options: {
          presets: ['@babel/preset-env', '@babel/preset-react'],
          plugins: ['@babel/plugin-proposal-class-properties'],
        },
      },
    },
  );

  addWebpackAlias({
    'react-native-linear-gradient': 'react-native-web-linear-gradient',
  });

  return config;
};

Здесь я использую псевдоним «response-native-linear-gradient» на «react-native-web-linear-gradient». Насколько я понимаю, весь импорт вроде

import LinearGradient from 'react-native-linear-gradient';

будет преобразован в

import LinearGradient from 'react-native-web-linear-gradient';

с помощью webpack при создании веб-приложения.

Однако я все еще получаю ту же ошибку, например, не использую псевдоним.

Что я не так.


person se22as    schedule 13.10.2020    source источник


Ответы (1)


addWebpackAlias не импортируется в конфигурацию, вы должны использовать встроенный override из custom-cra и ссылаться на его api для конфигурации веб-пакета

/* config-overrides.js */
const {
  override,
  addWebpackAlias,
  addBabelPlugins,
  addBabelPresets,
  babelExclude,
  path,
} = require('customize-cra');

module.exports = override(
  babelExclude([path.resolve("node_modules")]),
  ...addBabelPlugins('@babel/plugin-proposal-class-properties'),
  ...addBabelPresets('@babel/preset-env', '@babel/preset-react'),
  addWebpackAlias({
    'react-native-linear-gradient': 'react-native-web-linear-gradient',
  }),
);

Изменить: вы можете использовать babelExclude, чтобы исключить папку, которую вы не хотите переносить

person tuan.tran    schedule 13.10.2020
comment
Большое спасибо за ваш быстрый ответ, ваше решение работает очень хорошо, спасибо. Однако мне потребовалась небольшая настройка addWebpackModuleRule({ test: /\.js$/, use: 'babel-loader', exclude: /node_modules\/(?!()\/).*/ }),. Без этого мое веб-приложение не работает с /node_modules/react-native-gesture-handler/DrawerLayout.js SyntaxError:XXX/node_modules/react-native-gesture-handler/DrawerLayout.js: Support for the experimental syntax 'flow' isn't currently enabled (30:8): - person se22as; 13.10.2020