在我的react-native-web案例中,只需使用一个额外的webpack规则,就可以解决TypeError: Cannot assign to read only property 'exports' of object的问题。也许你可以参考一下。
npm install --save-dev react-app-rewired
在您的项目根目录中创建一个
config-overrides.js
文件。
const webpack = require('webpack');
const path = require('path');
module.exports = {
webpack: function (config, env) {
config.module.rules[1].use[0].options.baseConfig.extends = [
path.resolve('.eslintrc.js'),
];
delete config.resolve.alias['react-native'];
config.resolve.alias['react-native/Libraries/Components/StaticRenderer'] =
'react-native-web/dist/vendor/react-native/StaticRenderer';
config.resolve.alias['react-native'] = path.resolve(
'web/aliases/react-native',
);
config.plugins.push(
new webpack.DefinePlugin({
__DEV__: env === 'development',
}),
);
config.module.rules.push({
test: /\.(js|tsx?)$/,
use: {
loader: 'babel-loader',
},
});
return config;
},
paths: function (paths, env) {
paths.appIndexJs = path.resolve('index.web.js');
paths.appSrc = path.resolve('.');
paths.moduleFileExtensions.push('ios.js');
return paths;
},
};
同时创建一个
web/aliases/react-native/index.js
文件。
import {Text as RNText, Image as RNImage} from 'react-native-web';
export * from 'react-native-web';
export const ViewPropTypes = {
style: () => {},
};
RNText.propTypes = {
style: () => {},
};
RNImage.propTypes = {
style: () => {},
source: () => {},
};
export const Text = RNText;
export const Image = RNImage;
export const requireNativeComponent = () => {};
现在你只需要运行
react-app-rewired start
而不是
react-scripts start
。
require
,不应该引入其他的方式。现在有两种不兼容的方式,导致混乱不堪。有些需要使用require
,而另一些则需要使用import
,同时你的 babel 设置也会产生影响。 - sudo