Search code examples
webpackwebpack-2

Webpack Chunks In Separate Folder


I want to implement code-splitting feature in my app. I split my app by routes and for every route I user require.ensure to import component. I try to put all chunks in chunk folder, so I change output in config file:

output: {
   filename: "chunks/bundle[name].js"
}

But I got 404 error.

Error: Loading chunk 2 failed at HTMLScriptElement.onScriptComplete

So I leave it in folder where I have bundle file:

var webpack = require("webpack");
module.exports = {
    entry: "./js/app.js",
    output: {
        filename: "./bundle.js"
    },
    module: {
        rules: [
            {
                test: /\.vue$/,
                loader: "vue-loader"
            },
            {
                test: /\.js$/,
                loader:"babel-loader"                
            },
            {
                test: /\.css$/,
                loader: "style-loader!css-loader"
            },
            {
                test: /\.(eot|svg|ttf|woff|woff2)(\?\S*)?$/,
                loader: "file-loader?name=element-ui/[name].[ext]"
            }       
        ]
    },
    resolve: {
        extensions: [ ".json", ".js", ".vue", ".css" ]
    },
    watch: true
};

An now works, but I got chunk structure like this: folder chunk structure. How can I move all that chunks in only one folder. And is this proper way of using code-splitting feature.

I think I'm missing something. Please help!


Solution

  • First of all include path module at the top of webpack.config file.:

    var path = require("path");
    

    Because you have multiple chunk files, your output point need to have filename, and chunkFilename property with [name] or [id]. Problem with file structure is that you didn't define publicPath:

    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'dist'),
        publicPath: 'dist/',
        chunkFilename: '[name].js'
    }
    

    Now every chunk file and other bundles like main.js, vendor, manifest file will be in dist/ folder. Here is example of webpack.config.js file