Skip to content

Instantly share code, notes, and snippets.

@jcenturion
Last active November 15, 2022 14:49
Show Gist options
  • Save jcenturion/892c718abce234243a156255f8f52468 to your computer and use it in GitHub Desktop.
Save jcenturion/892c718abce234243a156255f8f52468 to your computer and use it in GitHub Desktop.

How to turn off Webpack code-splitting

Using Webpack import()

The following code will produce code-splitting in Webpack, which means that the source code will be split into several files that will be loaded async at runtime.. More info here;

import('./some-module').then((SomeModule) => {});

The problem

My application required to have two bundles:

  • one file bundle
  • async loading bundle

The problem is that Webpack does not have an option to turn off code-splitting.

Note: Using webpack: 2.5.0.

The solution

The first option was to try the following:

plugins: [
  new webpack.optimize.LimitChunkCountPlugin({
    maxChunks: 0
  })
]

By using maxChunks: 0, the code-splitting was not affected. However, when using maxChunks: 1, code-splitting was turned off but a runtime error appears __webpack_require__.e is not a function.

Note: This workaround was proposed at Option to disable code splitting completely

After researching a little bit about Babel's plugins.

module: {
  rules: [{
    test: /\.js$/,
    include: [
      path.resolve(__dirname, 'src')
    ],
    use: [{
      loader: 'babel-loader',
      options: {
        plugins: [
          'dynamic-import-webpack',
          'remove-webpack'
        ]
      }
    }]
  }
}

This approach is using two Babel's plugins dynamic-import-webpack and remove-webpack. So, how it works?:

  1. The first plugin transpiles import() to require.ensure
  2. The second plugin removes require.ensure from the code
@alejofernandez
Copy link

👏 👏 👏
+:100:

@Yugloocamai
Copy link

This feels pretty hacky to me.

@websharik
Copy link

websharik commented Nov 15, 2022

Still working with wp5 👍 Too require single file bundle for SSR...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment