Wepback. Loading chunk failed after using `import()`

坚强是说给别人听的谎言 提交于 2021-02-08 05:00:23

问题


I'm working on React project and I had found out that one of budles files is too big and I need to split it. So, I tried to use import() sintax:

import React from 'react';
import thumbnails from './thumbnails.json';

export default class Portfolio extends React.Component {
    constructor(props) {
        super(props);
        import('react-image-gallery').then(module => {
            const ImageGallery = module.default;
            this.galleries = thumbnails.map((thumbnail, i) => {
                let items = [];
                for (let i = 0; i < thumbnail.gallery.amount; i++) {
                    items.push({
                        original: `${thumbnail.gallery.href}/${i}.png`,
                        thumbnail: `${thumbnail.gallery.href}/${i}m.png`,
                    })
                }
                return (
                    <div className="gallery">
                        <ImageGallery key={i} items={items} thumbnailPosition="left" showPlayButton={false}
                                      onImageLoad={this.onGalleryLoad.bind(this, thumbnail.gallery.amount)}/>
                        <button className="gallery__close" onClick={this.onCloseClick.bind(this)}>&times;</button>
                    </div>
                )
            });
        });
    }

Portfolio is the main component for one page. Later, when I open the page, there's an error Uncaught (in promise) ChunkLoadError: Loading chunk 0 failed.
As I saw, JavaScript tries to load file 0.bundle.js from the portfolio directory. While needed chunk is 0.chunk.js that is located in the root directory.

Here's my Wepback config:

const TerserPlugin = require('terser-webpack-plugin');

module.exports = env => {
    const isDev = env.MODE === 'development';

    return {
        mode: isDev ? 'development' : 'production',
        devtool: 'source-map',
        entry: {
            './home/script': './home/script.jsx',
            './portfolio/script': './portfolio/script.jsx',
            './prices/script': './prices/script.jsx',
            './contacts/script': './contacts/script.jsx',
            './extra/script': './extra/script.jsx',
            './extra/locations/script': './extra/locations/script.jsx',
            './extra/poses/script': './extra/poses/script.jsx',
            './extra/stylists/script': './extra/stylists/script.jsx',
            './extra/studios/script': './extra/studios/script.jsx',
        },
        output: {
            path: __dirname,
            publicPath: __dirname,
            filename: '[name].bundle.js',
            chunkFilename: '[name].chunk.js',
        },
        module: {
            rules: [
                {
                    test: /\.jsx?$/,
                    exclude: /node_modules/,
                    use: {
                        loader: "babel-loader",
                        options: {
                            presets: ['@babel/preset-env', '@babel/react'],
                            plugins: [
                                '@babel/plugin-proposal-class-properties',
                                '@babel/plugin-transform-runtime',
                                '@babel/plugin-syntax-dynamic-import',
                            ]
                        }
                    }
                },
            ],
        },
        optimization: {
            minimize: !isDev,
            minimizer: [new TerserPlugin({
                test: /.js$/i,
                extractComments: false,
                terserOptions: {
                    output: {
                        comments: false,
                    },
                },
            })],
        },
        resolve: {
            extensions: ['.jsx', '.js'],
        }
    }
};

回答1:


Try changing your output object to

output: {
    ......
    chunkFilename: '[name].[chunkhash].js',
}

Check this out for reference https://github.com/webpack/webpack/issues/9207#issuecomment-499448929




回答2:


I've found the answer. To escape searching in subrirectories, you should use publicPath: '/' in the output option of webpack. It was sugested to use chunk hashes, but as I tried it, it's not really nesessary. The whole solution is here:

output: {
    path: __dirname,
    publicPath: '/',
    filename: '[name].bundle.js',
    chunkFilename: './assets/chunks/[name].chunk.js',
}

The ./assets/chunks/ part is not required. It's just for holding all chunks in one directory



来源:https://stackoverflow.com/questions/62846070/wepback-loading-chunk-failed-after-using-import

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!