有外包和主应用。两者都使用 webpack 和 babel。外部包使用 webpack 构建并在其中做出反应。
外部库babel.config.js
module.exports = {
presets: [
[
'@babel/preset-env',
{
modules: false,
},
],
'@babel/preset-react',
],
plugins: ['emotion', '@babel/syntax-dynamic-import'],
};
外部库webpack.config.js
const path = require('path');
const isProduction = process.env.NODE_ENV === 'production';
const config = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index.js',
assetModuleFilename: 'assets/[contenthash][ext][query]',
clean: true,
},
externals: {
react: 'React',
'react-dom': 'ReactDOM',
emotion: 'emotion',
reactEmotion: 'react-emotion',
},
module: {
rules: [
{
test: /\.(js|jsx)$/i,
loader: 'babel-loader',
},
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(eot|svg|ttf|woff|woff2|png|jpg|gif)$/i,
type: 'asset',
},
],
},
};
module.exports = () => {
if (isProduction) {
config.mode = 'production';
} else {
config.mode = 'development';
}
return config;
};
React 主应用程序使用这个包:
import('EXTERNAL_PACKAGE_NAME').then((chat) => {
// code does not reaches this line
debugger;
const a = chat.ReactFromModule === React;
});
主应用webpack.config.js
module.exports = () => {
const nodeEnv = process.env.NODE_ENV;
const isProd = nodeEnv === 'production';
return {
mode: nodeEnv,
resolve: {
extensions: ['.js', '.jsx', '.css', '.styl'],
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
include: [res('src'), /node_modules\/(?!{EXTARNAL_PACKAGE_NAME})/],
use: ['thread-loader', 'babel-loader'],
},
],
},
};
};
在那种情况下出现错误:
index.js:2 Uncaught (in promise) ReferenceError: React is not defined
我尝试使用 webpack 配置 externals 字段,但这没有帮助。
我尝试将 libraryTarget 添加到外部包配置
output: {
libraryTarget: 'umd',
library: 'Chat',
umdNamedDefine: true,
}
externals: {
react: 'react',
'react-dom': 'reactDOM',
emotion: 'emotion',
reactEmotion: 'react-emotion',
},
出现错误:
Module not found: Error: Can't resolve 'reactDOM' in PATH
外部库是应该提供 React 的库吗?您使用 React 配置了
externals
字段。
来自webpack 文档:
外部配置选项提供了一种排除方法 来自输出包的依赖项。相反,创建的包 依赖于该依赖项存在于消费者的(任何 最终用户应用程序)环境。此功能通常是最 对库开发人员有用,但是有多种 申请它。
这意味着您的库也依赖于另一个包来提供 React。
查看这个 SO 答案 https://stackoverflow.com/a/54888897/8050896,强制 webpack 解析模块可能会有所帮助。
{
resolve: {
modules: [
path.resolve(__dirname, 'node_modules'),
path.resolve(__dirname, 'node_modules/ui/node_modules'),
],
},
}