我正在创建一个用Babel编译并由Webpack捆绑的React / Redux应用程序。我想实现插件功能。因此,我将代码拆分与Dynamic import()结合使用,以为每个插件划分主要捆绑包。但是,如果我在很多地方都需要同一个插件,Webpack将为使用的任何import()捆绑一个捆绑包并对其进行迭代(0.bundle.js,1.bundle.js等)。我尝试在import()的注释中使用webpackChunkName:“ MyPlugin”,以为如果我导入具有相同块名称的Bunble,它将在捆绑时替换另一个,但是由于我使用babel-plugin-dynamic-import-webpack ,webpackChunkName似乎不再起作用。由于项目的私密性,我无法提供任何可测试的演示。有想法吗?
import( /* webpackChunkName: "MyPlugin" */ `./plugins/MyPlugin.jsx` );
.babelrc
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
],
"plugins": [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-syntax-dynamic-import",
"@babel/plugin-syntax-jsx",
"@babel/plugin-transform-object-assign",
"dynamic-import-webpack",
["import", { "libraryName": "antd", "libraryDirectory": "lib"}, "ant"]
],
"env": {
"node": {
"plugins": [
["babel-plugin-transform-require-ignore",
{"extensions": [".less", ".scss", ".png", ".jpg"]}
]
]
},
"test": {
"presets": [["env", {"modules": "commonjs"}]]}
},
"comments": true
}
webpack.config.js
[...]
module.exports = {
entry: entry,
output: {
path: path.join(__dirname, 'build'),
filename: 'js/[name].js',
chunkFilename: 'js/[name].bundle.js',
publicPath: "/",
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: [/node_modules/],
use: {
loader: 'babel-loader',
query: {
plugins: [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-syntax-dynamic-import",
"@babel/plugin-syntax-jsx",
"@babel/plugin-transform-object-assign",
"dynamic-import-webpack",
["import", { "libraryName": "antd", "libraryDirectory": "lib"}, "ant"]
],
presets: [
"@babel/preset-env",
"@babel/preset-react"
]
}
}
},
[...]
答案 0 :(得分:0)
我用require.ensure()代替了动态import()。
const MyPlugin = require.ensure([], function (require) {
const plugin = require('./plugins/MyPlugin/MyPlugin.jsx');
return new plugin.default;
}, "MyPlugin");