首页 > 解决方案 > Webpack 静态和动态导入都导致无块

问题描述

我一直在为某些事情苦苦挣扎(做出反应,但没关系)。想象一下以下设置:

// modules/A/index.ts
export { actions } from '/actions'
export { default as RootComponent } from './component' // imagine this to be big, I tried adding 250kb of data to it.
export { default as reducer } from './reducer'
export { default as saga } from './saga'

现在..在应用程序中,有以下内容:

// index.js
import {actions} from './modules/A';

const LazyComponent = React.lazy(() => import('./modules/A').then(res => {
  // doing something with the reducer/saga
  return {default: res.RootComponent}
}));

// LazyComponent as a route, using an action from actions to trigger something (if present)

所有这一切都很好,除了当我从模块中静态导入动作的那一刻,将不再生成任何块,一切都在主 js 中结束。如果我要从模块中的动作文件本身导入动作,它将动态导入生成一个块,如所需。

如果可以采取任何措施来获得我想要的效果:从模块中静态导入某些内容,但仅按需加载其余内容(因为大小)?

这个想法是,模块可能会在稍后被提取为依赖项(es 模块),然后 pkg.module 将是一些索引,那么如何支持这样的代码拆分呢?

简化的 Webpack 配置(从另一个项目复制,还没有真正通过它)(v4.43):

const config = {
    target: 'web',
    entry: {
        app: './src/index.tsx',
    },

    output: {
        filename: '[name].[chunkhash].bundle.js',
        path: path.join(__dirname, 'dist'),
        publicPath: '/',
    },

    resolve: {
        extensions: ['.tsx', '.ts'],
        modules: [path.resolve(__dirname, 'src'), 'node_modules'],
    },

    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: [
                    {
                        loader: 'thread-loader',
                        options: {
                            poolTimeout: isProduction ? 500 : Infinity,
                        },
                    },
                    {
                        loader: 'ts-loader',
                        options: {happyPackMode: true},
                    },
                ],
            },
            {
                test: /\.css$/i,
                use: ['style-loader', 'css-loader'],
            },
            {
                test: /\.(ttf|eot|svg|jpg|gif|png|woff(2)?)(\?[a-z0-9]+)?$/,
                loader: 'file-loader',
            },
        ],
    },

    plugins: [
        ...(isProduction ? new CleanWebpackPlugin() : []),
        new webpack.DefinePlugin({
            PRODUCTION: isProduction,
        }),
        new htmlWebpackPlugin({template: './src/index.html'}),
        new CopyWebpackPlugin({
            patterns: [
                {
                    context: './public',
                    from: '**/*',
                },
            ]
        }),
        new CircularDependencyPlugin({
            exclude: /node_modules/,
            failOnError: true,
        }),
    ],

    devServer: { /* blabla*/ },
    optimization: {
        noEmitOnErrors: true,
    },
    stats: {
        warningsFilter: /export .* was not found in/,
    },
}

标签: javascriptwebpackcode-splitting

解决方案


推荐阅读