Не удается присвоить псевдоним react-native-linear-gradient для react-native-web-linear-gradient для react native web app

#react-native #react-native-web

#react-native #react-native-web

Вопрос:

У меня есть приложение react-native с одним экраном, содержащим 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 этому.

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

  • «react-native-web-linear-gradient»: «1.1.1»
  • «react-app-rewired»: «^ 2.1.6»,
  • «customize-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;
};
  

Здесь я изменяю ‘react-native-linear-gradient’ на ‘react-native-web-linear-gradient’. Я понимаю, что весь импорт, такой как

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

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

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

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

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

Что у меня не так.

Ответ №1:

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

 /* 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, чтобы исключить папку, которую вы не хотите переносить

Комментарии:

1. Большое вам спасибо за быстрый ответ, ваше решение работает отлично, спасибо. Однако мне понадобилась небольшая настройка 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):