The code separation feature separates the code into different bundles, which can then be loaded on demand or loaded in parallel. Code separation can be used to obtain smaller bundles, and to control the load priority of resources, which, if used reasonably, can significantly affect load times.
There are three common methods of code separation:
- Entry start:
entry manually detach the code using the configuration.
- Prevent duplication: Use deduplication
CommonsChunkPlugin and detach chunk.
- Dynamic import: Use the module's inline function to detach the code.
1. Entrance starting point (entry points)
This is by far the simplest and most intuitive way to separate code. However, this is a more manual configuration and there are some pitfalls that we will address. Let's take a look at how to detach another module from the main bundle:
as mentioned earlier, there are some problems with this approach:
- If the portal chunks contains duplicate modules, those repeating modules are introduced into each bundle.
- This approach is not flexible enough, and the core application logic cannot be dynamically split code.
2. Prevent duplication (prevent duplication)
CommonsChunkPluginA plug-in can extract a common dependency module into an existing portal chunk, or extract a newly generated chunk. Let's use this plugin to remove the duplicate modules from the previous example lodash :
3. Dynamically import (dynamic imports)
when it comes to dynamic code splitting, Webpack provides two similar techniques. For dynamic import, the first and preferred option is to use the syntax that conforms to the ECMAScript proposal import() . The second is the use of Webpack-specific require.ensure . Let's first try to use the first kind of ...
Before we start this section, remove the redundant and from the configuration entry CommonsChunkPlugin , because they are not needed in the next demo:
src/index.js:
used in comments webpackChunkName . Doing so will cause our bundle to be named lodash.bundle.js , not [id].bundle.js .
Webpack Learning--code spliting (code separation)