Search code examples
vue.jswebpackvue-cli-4

Prevent JS files from splitting into chunks (vue cli 4 + webpack)


npm run build

Is creating multiple 'chunk' files, such as:

  1. /dist/js/app.*.js
  2. /dist/js/chunk-2413.js
  3. /dist/js/chunk-5133.js

My goal is to have them all within a single app.*.js file!

I've set 'splitChunks' to false in vue.config.js, however this won't put all the chunks in the same app.*.js file, since I'm importing a bunch of text files into the project (I'm opting for text files over internal configuration variables as I prefer this format for the purpose of the application).

Here's my code that successfully returns promises and loads the data from the text files into the allContents array:

const textFiles = require.context('../assets/textfiles', true, /\.txt$/i);
var self = this;    
var fileContents = textFiles .keys();
fileContents.forEach(function (item, index){
    console.log(item+' - '+index);
    var val = import('raw-loader!../assets/textFiles '+item.replace('.',''));
    val.then( (resp) => {
        console.log(resp.default);
        self.allContents.push(resp.default);
    });
});

The data from these text files, is causing the 'dist/js/chunk...' files to be created. What I need to is stop them from doing that - but how? Is there a way to stop this behaviour?

Update to include vue.config.js:

const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin')

module.exports = {
    publicPath: '',
    productionSourceMap: false,
    css: {
        extract: false,
    },
    configureWebpack: {
        optimization: {
            splitChunks: false
        },
        plugins: [
            new ScriptExtHtmlWebpackPlugin({
                preload: /\.js$/,
                defaultAttribute: 'async'
            })
        ]       
    },
    chainWebpack: config => {
        config.module
          .rule('raw')
          .test(/\.txt$/)
          .use('raw-loader')
          .loader('raw-loader')
          .end()
  }
}

Sample data from one of the chunk js files: (it's just loading in a txt file which has contents like '### Config: ### blah blah')

(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["chunk-2d0a2dc4"],{"005c":function(e,t,n){"use strict";n.r(t),t["default"]="export default \"##########\\r\\n# Config:\\r\\n##########\\r\\n\\r\\n$type: Chat\";"}}]);

Solution

  • Using raw-loader with "import" syntax is the reason make it autosplitting. And the path to textFiles in your code has a space at the end, I dont know is it a typo

    var val = import('raw-loader!../assets/textFiles '+item.replace('.',''));
    

    You can try change to this way. It may help as a workaround solution to prevent splitting

    fileContents.forEach(function (item, index) {
      console.log(item + ' - ' + index)
      var val = require('raw-loader!./assets/textFiles' + item.replace('.', ''))
      self.allContents.push(val.default)
    })
    

    Hope this help