问题描述
我正在创建一个用Babel编译并由Webpack捆绑的React / Redux应用程序。我想实现插件功能。因此,我将代码拆分与Dynamic import()结合使用,以为每个插件划分主要捆绑包。但是,如果我在很多地方都需要同一个插件,Webpack将为使用的任何import()捆绑一个捆绑包并对其进行迭代(0.bundle.js,1.bundle.js等)。我尝试在import()的注释中使用webpackChunkName: MyPlugin,以为如果我导入具有相同块名称的Bunble,它将在捆绑时替换另一个,但是由于我使用babel-plugin-dynamic-import-webpack ,webpackChunkName似乎不再起作用。由于项目的私密性,我无法提供任何可测试的演示。知道吗?
I am creating a React/Redux App compiled with Babel and bundled by Webpack. I want to implement a plugin feature. So I use Code Splitting with Dynamic import() to divide the main bundle for each plugin. However, if I need the same plugin in many place, Webpack will bundle a bundle for any import() used and iterate it (0.bundle.js, 1.bundle.js, ...). I try to use webpackChunkName: "MyPlugin" in comment in import() thinking that if I import a bunble with the same chunk name, it will replace the other one while bundling, but since I use babel-plugin-dynamic-import-webpack, webpackChunkName don't seem to work anymore. Due to project privacy, I can't provide any testable demo. Any idea?
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
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"
]
}
}
},
[...]
推荐答案
我用require.ensure()替换了动态import()。
I replaced the Dynamic import() by a require.ensure().
const MyPlugin = require.ensure([], function (require) {
const plugin = require('./plugins/MyPlugin/MyPlugin.jsx');
return new plugin.default;
}, "MyPlugin");
这篇关于如何防止动态导入来复制包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!