Webpack code separation

Code separation: Separate code into different bundles for later loading on demand or in parallel. There are three ways to separate code:

  • 1. File entry
  • 2. Avoid repetition
  • 3. Dynamic import

Entry mode separation:

Two entries are configured in Webpack:

const path = require('path'); module.exports = { entry: { index: './src/index.js', print: './src/print.js' }, output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist') } }; Copy the codeCopy the code

The common module is introduced in both index.js and print.js:

import common from './common'; Copy the codeCopy the code

The output directory contains two bundles. This results in code separation, but there are two problems with this approach:

  • 1. Both bundles introduce the common module, causing double references.
  • 2. Not flexible enough to dynamically split core code logic.

To prevent duplication 1, pull out the public module display in webpack.config.js. Common is the public module introduced in index.js and print.js: \

entry: { index: { import: './src/index.js', dependOn: 'shared' }, print: { import: './src/print.js', dependOn: 'shared'}, shared: './ SRC /common.js'}, copy the codeCopy the code

Configuration runtimeThunk:



Then running WebPack generates four bundles:



From the above we know that, except for the formationshared.bundle.js.index.bundle.js 和 another.bundle.jsIn addition, one is generatedruntime.bundle.jsFile. SplitChunksPlugin SplitChunksPlugin SplitChunksPlugin SplitChunksPlugin SplitChunksPlugin SplitChunksPlugin

const path = require('path'); module.exports = { entry: { index: './src/index.js', print:'./src/print.js' }, output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist') }, optimization: { splitChunks: { chunks: 'all' } } }; Copy the codeCopy the code

Run webPack as follows:

Dynamic import: Only one entry is configured in Webpack:

const path = require('path'); module.exports = { entry: { index: './src/index.js' }, output: { filename: 'index.bundle.js', path: path.resolve(__dirname, 'dist') } }; Copy the codeCopy the code

Using dynamic imports in index.js files:

Import ('/common '). Then (() = > {the console. The log (' dynamic import success); });Copy the code

Running WebPack generates two bundles: