我在react-loadable中遇到了一个问题,我有一个很大的组件列表,这些组件可能会呈现,也可能不会呈现,这取决于用户生成的内容。我使用了一个switch语句来呈现正确的结果。
用户生成的内容的(简化)列表可能如下所示:
const content = ['Paragraph', 'Image', 'Paragraph', 'Canvas'];
现在,我想要做的是只将使用的组件放入包中。取而代之的是,所有包含在以下切换用例中的元素都包含在包中。为什么?
const collection = (name) => {
switch(name) {
case 'Paragraph':
return Loadable({
loader: () => import('dynamic-paragraph-component'),
loading(){ return null }
})
case 'Video':
return Loadable({
loader: () => import('dynamic-video-component'),
loading() { return null }
})
// etc
}
}例如,即使不使用dynamic-video-component,它也会在捆绑包中结束。有没有办法防止这种情况发生?
当前的webpack设置与Webpack 4
//----------------------------------
//
// Bundler
//
//----------------------------------
import webpack from 'webpack';
import path from 'path';
import { ReactLoadablePlugin } from 'react-loadable/webpack';
module.exports = (files) => {
console.log(files);
return {
mode: 'production',
entry: './src/client/index.js',
output: {
filename: './main.pkgd.js',
chunkFilename: './[name].pkgd.js',
path: path.resolve(__dirname, 'tmp'),
publicPath: '/',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
babelrc: false,
presets: [
[
'env',
{
modules: false,
targets: {
browsers: ['last 2 versions'],
},
},
],
'flow',
'react',
],
plugins: [
'transform-class-properties',
'syntax-dynamic-import',
'react-loadable/babel',
],
},
},
],
},
optimization: {
splitChunks: {
cacheGroups: {
default: false,
vendors: false,
// vendor chunk
vendor: {
name: 'vendor',
chunks: 'all',
test: /node_modules/,
priority: 20,
reuseExistingChunk: true,
enforce: true,
},
common: {
name: 'main',
minChunks: 1,
chunks: 'initial',
priority: 10,
reuseExistingChunk: true,
enforce: true,
},
},
},
},
plugins: [
new webpack.DefinePlugin({
__isBrowser__: 'true',
env: {
NODE_ENV: JSON.stringify('production'),
},
}),
new ReactLoadablePlugin({
filename: './tmp/react-loadable.json',
}),
],
};
};发布于 2018-09-05 07:16:06
您设置它的方式看起来是正确的,所以我打赌问题出在您的webpack.config.js文件中。
假设您使用的是Webpack 4,则需要引用code-splitting docs。
具体地说,请确保已配置chunkFilename选项。此外,您还可以添加诸如/* webpackChunkName: "dynamic-video-component" */之类的注释指令,以简化调试。
https://stackoverflow.com/questions/52174468
复制相似问题