您可以克隆我的最小存储库 https://github.com/rockmandash/webpack-chunks-question
或者查看下面的代码
page1.js
import 'core-js';
console.log('I am page1');
page2.js
import 'core-js';
import 'react';
import 'react-dom';
console.log('I am page2');
我的 webpack 配置:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const entriesFilePath = [
require.resolve('./src/page1.js'),
require.resolve('./src/page2.js'),
];
const mode = 'development';
const webpackConfig = entriesFilePath.map((entrieFilePath) => {
const fileName = path.basename(entrieFilePath, path.extname(entrieFilePath));
// fileName would be page1 and page2
return {
mode,
devtool: 'cheap-module-source-map',
entry: {
[fileName]: entrieFilePath,
},
output: {
filename: 'static/js/[name].js',
chunkFilename: 'static/js/[name].chunk.js',
},
optimization: {
splitChunks: {
chunks: 'all',
},
},
plugins: [
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin(
Object.assign(
{},
{
inject: true,
filename: `${fileName}.html`,
},
),
),
].filter(Boolean),
};
});
module.exports = webpackConfig; // I have to export an array, because in the future, I need to do something else.
生成的 dist 文件夹如下所示:
dist
/page1.html
/page2.html
/static
/js
/page1.js.map
/vendors~page2.chunk.js.map
/vendors~page1.chunk.js // this includes core-js !!!!
/page1.js
/page2.js
/vendors~page1.chunk.js.map
/vendors~page2.chunk.js // this includes core-js too !!!!
/page2.js.map
你看,生成的两个 block 都包含 core-js,我怎样才能让我的 webpack 配置足够智能,自动将 core-js 或其他常见 vendor 文件开箱即用?
最佳答案
您不需要在任何地方导入 core-js 。创建一个 .babelrc 文件。
{
"presets": [
[
"@babel/preset-env",
{
"debug": true,
"useBuiltIns": "usage",
"corejs": 3
}
]
]
}
安装@babel/core、@babel/polyfill、@babel/preset-env、babel-loader
添加到webpack
const optimization = {
splitChunks: {
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/](react|react-dom)[\\/]/,
name: 'vendor',
chunks: 'all',
}
}
}
};
module: {rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]},
看一下我的解决方案,有完整的代码。使用 core-js。当需要时,他只使用部分聚纤维。 https://github.com/tomik23/webpack-babel-corejs/blob/master/webpack.config.js#L17
代码中需要的第二个解决方案是使用 spliChunks https://github.com/tomik23/photoBlog/blob/master/config/webpack.config.js#L31
附注如果你以这种方式导入'core-js';如果您使用我的方法,则下载整个 core-js,然后 core-js 只选择需要的内容,并且包更小。
关于javascript - 在具有多个条目的Webpack v4中,我的splitChunks没有优化,如果我的两个页面包含core-js,它们都会得到一份副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56916226/