1️⃣ What is Webpack?What is the core concept?
Webpack is a static module bundler.
Core idea:
- Treat all resources as modules (JS, CSS, images, fonts, etc.)
- Analyze the relationship between modules through dependency graph
- The final output is a bundle (or multiple chunks) that the browser can run.
One sentence explanation:
Webpack modularizes all resources in the front-end project and finally packages and outputs them uniformly.
2️⃣ Core concepts of Webpack (very important)
① Entry
Tells Webpack which file to start analyzing the dependency graph from.
entry: './src/index.js'Can be multiple entries:
entry: {
main: './src/main.js',
admin: './src/admin.js'
}② Output
Decide where to output the packaged file and what to call it.
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}③ Loader (module converter)
Webpack can only handle JS and requires loader extension capabilities.
Common loaders:
| Resources | Corresponding loader |
|---|---|
| CSS | css-loader, style-loader |
| LESS | less-loader |
| Image | url-loader/file-loader (Webpack5→asset module) |
| ES6 | babel-loader |
| Vue | vue-loader |
| TS | ts-loader |
Example:
module: {
rules: [
{ test: /\.css$/, use: ['style-loader', 'css-loader'] }
]
}④ Plugins (plug-in system, Webpack’s strongest capability)
Loader handles a type of file, and Plugin handles the entire build process.
Common plug-ins:
| Plug-in | Function |
|---|---|
| html-webpack-plugin | Generate HTML and automatically inject bundles |
| clean-webpack-plugin | Clean dist |
| mini-css-extract-plugin | Extract CSS |
| define-plugin | Inject environment variables |
| terser-webpack-plugin | Compress JS |
| css-minimizer-webpack-plugin | Compress CSS |
⑤ Mode
Two environments:
mode: 'development'
// 或
mode: 'production'Difference:
| mode | features |
|---|---|
| development | No compression, source map included, module identifier readable |
| production | automatic compression, tree shaking, scope hoisting |
⑥ DevServer (development server)
Used for local development and supports hot updates (HMR).
devServer: {
hot: true,
port: 8080,
open: true
}⑦ Source Map (location code error)
Most common settings:
devtool: 'source-map'3️⃣ Webpack packaging process
Webpack build process:
- Read configuration (entry)
- Parse the entry file and build AST
- Recursively build a dependency graph (module graph) layer by layer according to dependencies
- Loader converts the corresponding file content
- Plugin intervenes in the build life cycle (optimize, emit, etc.)
- generate chunk → bundle
- Output is generated to the output directory
If you could describe it in one sentence:
Webpack recursively builds the dependency graph starting from the entry point, uses loader to process the module, then uses the plugin plug-in mechanism to extend the build process, and finally outputs the optimized bundle file.
4️⃣ Webpack common optimization (high frequency of interviews)
① Tree Shaking (remove unused code)
Production mode is automatically enabled and requires ES Module.
② Code Splitting
Separate common code via dynamic imports or SplitChunks.
import('./views/About.vue')③ Cache optimization (long-term cache)
Use:
output: {
filename: '[name].[contenthash].js'
}④ Compression optimization
Production mode enables minimization but does not automatically install third-party CSS plugins:
- The selected Webpack version’s default minimizer handles JS.
- CSS handling depends on native support and configuration; external CSS extraction needs an appropriate explicit minimizer.Optimization configuration.
⑤ Image optimization
Use asset module or image-minimizer-webpack-plugin.
5️⃣ The difference between Webpack and Vite (interviews are very frequent)
| Comparison point | Webpack | Vite |
|---|---|---|
| Build method | Bundle (package and run) | Native ESM (load on demand) |
| Startup speed | Slow (many dependencies) | Very fast |
| HMR | Repackaging modules | Hot updates on demand |
| Ecology | Mature, powerful | New, gradually improving |
| Applicable projects | Large systems, complex construction | Rapid development, lightweight projects |
One sentence summary:
Vite has a fast development environment, strong Webpack construction capabilities, mature ecology, and is suitable for complex projects.
6️⃣ Webpack common interview questions (give you a set)
The following questions are required for intermediate and advanced Webpack interviews:
① What is the difference between Loader and Plugin?
- Loader: Convert a certain type of module (file level)
- Plugin: Executed in the complete life cycle of Webpack (overall level)
② Why is Webpack packaging slow?How to optimize?
- Persistent caching (explicitly set cache.type to filesystem)
- Multi-process (thread-loader)
- Reduce loader scope (include/exclude)
- Disable unnecessary source maps
- Use CDN, externals
③ What is the principle of Tree Shaking?
- Depends on ES Module static structure
- Analyze import/export
- Remove unreferenced code
- Use Terser to do DCE (dead code elimination)
📌 Finally, I’ll give you one—Webpack basic summary in one sentence)
Webpack is a module packager that builds a module dependency graph through Entry, Output, Loader, and Plugin, and then uses Plugin to extend the entire life cycle, and finally outputs an optimized bundle.Common optimizations include Tree Shaking, Code Splitting, persistent caching, compression optimization, separated CSS, etc.
🔥 Real Interview Webpack High Frequency 20 Questions and Answers
1. What is Webpack?What is its core concept?
Answer: Webpack is a static module packager that converts all resources in the project (JavaScript, CSS, images, fonts, etc.) into files (bundle) that can be run in the browser by parsing dependencies. The core concepts of Webpack are:
- Entry: Entry file, tells Webpack where to start building the dependency graph.
- Output: Output file, specify the storage location of the packaged file.
- Loader: Allows Webpack to handle non-JavaScript resources (such as CSS, images, fonts, etc.).
- Plugin: Extend the functionality of Webpack through the plug-in system.
2. What is the difference between Loader and Plugin?
Answer:
- Loader: Responsible for converting the content of files, usually used to process non-JavaScript files (such as CSS, images, TypeScript, etc.).It is a file level operation.
- Plugin: used to extend the functionality of Webpack and perform more complex tasks, such as compression, optimization, generation of HTML files, etc.It is a global level operation and handles the entire build process.
3. What is Tree Shaking in Webpack?
Answer: Tree Shaking is a technique for eliminating unused code in JavaScript.Webpack statically analyzes ES6 modules (import/export) to determine which code is unused and removes it from the final bundle.It is typically enabled in production mode and relies on the static structure of ES modules.
4. What is Code Splitting?How to achieve?
Answer: Code Splitting refers to splitting code into multiple files so that they can be loaded on demand.It improves the initial loading speed of your app.Webpack provides three ways to implement code splitting:
- Entry Point Segmentation: Implement different entry files through multiple entries.
- On-demand loading (Dynamic Import): Use
import()to dynamically import modules, and Webpack will automatically split the code according to needs. - SplitChunksPlugin: A plug-in provided by Webpack that automatically analyzes the code and extracts common modules into independent files.
5. What is devServer in Webpack?
Answer: devServer is a development server for Webpack that provides hot module replacement (HMR) and live reloading capabilities.It helps developers quickly preview projects when developing locally, and provides functions similar to HTTP servers. Common configurations:
devServer: {
contentBase: './dist',
hot: true,
open: true,
port: 8080
}6. What are contenthash and chunkhash in Webpack?
Answer:
chunkhash: Hash value generated based on chunk content, often used in file names for cache control.contenthash: A hash value generated based on the file content. It is recommended to be used in a production environment to ensure that the file name will also change when the file content changes.
output: {
filename: '[name].[contenthash].js'
}7. How does Webpack handle dependencies?
Answer: Webpack recursively builds module dependency graphs by statically analyzing import or require in the code.During the build process, Webpack loads each module one by one and processes them, ultimately generating one or more bundled files.
8. How does Webpack 5 handle Node.js core modules?
Answer: Webpack 5 removes automatic polyfill for Node.js core modules.If you need to use Node core modules (such as crypto, path, etc.), you need to configure it manually or use resolve.fallback configuration to provide browser-side polyfill.
resolve: {
fallback: {
"crypto": require.resolve("crypto-browserify"),
"stream": require.resolve("stream-browserify"),
}
}9. Why does Webpack use source map and what is its role?
Answer: source map is a technology that maps compressed code back to source code, helping developers view the original source code and locate errors during browser debugging. Common configurations:
devtool: 'source-map'10. What is hot module replacement (HMR) in Webpack?
Answer: HMR is a feature provided by Webpack that allows only the changed modules to be updated after code modifications without refreshing the entire page.This greatly improves development efficiency and avoids loss of application state.
11. How does Webpack optimize packaging performance?
Answer:
- Cache optimization: explicitly enable filesystem caching; development defaults to memory caching and production disables it.
- Reduce module parsing time: Use
includeandexcludeto limit the application scope of Loader. - Code Splitting: Split code through dynamic import or SplitChunksPlugin.
- Tree Shaking: Remove unused code.
- Parallel processing: Use
thread-loaderto enable multi-process builds.
12. What is the externals configuration item in Webpack?
Answer: externals is used to configure to exclude external dependencies from packaging so that they are not packaged by Webpack.Often used to exclude common libraries (such as React, Vue), etc., to reduce the size of packaged files.
externals: {
react: 'React',
'react-dom': 'ReactDOM'
}13. What is the publicPath configuration item in Webpack?
Answer: publicPath specifies the public URL path of the resource.It can be a CDN address, a relative path, or an absolute path.publicPath is usually used to specify the storage location of packaged resource files.
output: {
publicPath: '/assets/'
}14. How to implement Webpack’s persistent cache?
Answer: Webpack 5 supports persistent caching with an explicit filesystem cache.type; development defaults to memory caching and production disables it.Cache documentation.
cache: {
type: 'filesystem'
}15. What are the module.rules configuration items in Webpack?
Answer: module.rules is used to define how to handle different types of files (modules), and configure Loader to convert modules.Each rule can specify test (matching files) and use (loader to use).
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
}16. What does resolve.alias in Webpack do?
Answer: resolve.alias is used to set the module path alias and simplify the module introduction path.For example, map a folder or module to an alias to reduce the trouble of writing long paths.
resolve: {
alias: {
'@components': path.resolve(__dirname, 'src/components/')
}
}17. Why use html-webpack-plugin?
Answer: html-webpack-plugin is used to automatically generate HTML files and automatically inject all resources packaged by Webpack (such as JS and CSS files) into HTML to avoid manual updates.
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
})
]
}18. What are the main improvements of Webpack 5 compared to Webpack 4?
Answer:
- Module Federation: Supports micro front-end architecture.
- Persistent Cache: Greatly improves build speed.
- Remove polyfill of Node.js core module: reduce packaging size.
- Better Tree Shaking support: Improve packaging performance.
19. What are file-loader and url-loader?What's the difference?
Answer:
file-loader: Copies the file to the output directory and returns the URL of the file.url-loader: Function is similar tofile-loader, but when the file is smaller than the specified size, the file is converted into a Data URL to avoid sending HTTP requests.
Difference:
file-loaderalways returns a file path, whileurl-loadermay return a Data URL.
20. How to implement image compression in Webpack?
Answer: Use image-webpack-loader or an image optimization plugin. url-loader only inlines Data URLs or emits files; it does not compress images.url-loader documentation.
module: {
rules: [
{
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: 'image-webpack-loader',
options: {
bypassOnDebugWebpack application summary two
Differences between module, chunk and bundle
- module --> Each source code file is a module, and everything in webpack is a module.
- chunk --> Merged from multiple modules, such as entry, import, splitChunk.Similar to a block of code in memory that has not yet been produced
- The final output file of the bundle, each chunk will generate a bundle file
Entry is the entry file of webpack and can generate chunk names by key names. import can generate a chunk, which is introduced into html by default. Define splitChunks in optimization to cache groups and name chunks through cacheGroups, and then introduce or exclude a chunk file in htmlWebpackPlugin.
The difference between loaders and plugins
- Both are intended to extend the functionality of webpack.The loader only focuses on the field of converting files (transform), completing compression, packaging, and language translation; while the plugin is not only limited to packaging and loading of resources, it can also package optimization and compression, redefine environment variables, etc.
- The loader runs before packaging files (loader is a preprocessing file when the module is loaded); plugins work throughout the compilation cycle
- A loader has a single responsibility and only needs to complete one conversion.A loader is actually a Node.js module.When multiple loaders need to be called to convert a file, each loader will be executed sequentially in a chain.
- Many events will be broadcast during the life cycle of webpack running. The plugin will listen to these events and change the output results at the appropriate time through the API provided by webpack.
- Loader module converter, such as less --> css, identifying image formats
- plugins extension plug-ins, such as htmlWebpackPlugin, friendlyLoaderWebpackPlugin, bundleAnalyzerPlugin, CleanWebpackPlugin, MiniCssExtractPlugin, ParallelUglifyPlugin,
webpack.IgnorePlugin,webpack.DefinePlugin
What are the commonly used loaders https://www.webpackjs.com/loaders/ What are the commonly used plugins https://www.webpackjs.com/plugins/
Optimize babel-loader
module: {
rules: [
{
test: /\.js$/,
// loader: ['babel-loader?cacheDirectory'], // 没有修改的es6代码不会重新编译
use: {
loader: 'babel-loader',
options: {
presets: [
["@babel/preset-env"],
{
useBuiltIns: 'entry',
corejs: 3,
targets: 'last 2 Chrome versions', // 指定兼容性
// use3rBuiltIns: 'false' 不对polyfill做操作。如果引入@babel/polyfill,则无视配置的浏览器兼容性,引入所有polyfill
// use3rBuiltIns: 'entry' 根据浏览器的兼容性,引入浏览器不兼容的polyfill。兼容的就不会引入了
// use3rBuiltIns: 'usage',根据配置的浏览器兼容性,以及代码中用到的api来进行polyfill的按需添加
// 'corejs':2的时候需要在入口文件中手动添加import '@babel/polyfill',会自动动根据browserlistrc替换成浏览器不兼容的所有polyfill
// 这里需要指定core-js版本,如果”corejs“:3,则import `@babel/polyfill` 需要改成 import 'core-js/stable'; import 'regenerator-runtime/runtime'
// core-js@2 分支中已经不会再添加新特性,新特性都会被添加到core-js@3,比如,Array.prototype.flat()
}
]
}
},
include: srcPath,
// exclude: /node_modules/
},
]
}When configuring babe-loader, write an include and exclude to reduce unnecessary code.
- cache-loader generates cacheKey as the file name based on the version number file name to see if the file exists. If it exists, it compares mtime (modify time). If the same return cache is used, if the following loader is not used, it is lightweight and does not compare the content.
- babel-loader generates cacheKey as the file name through the file, option, and version number. It reads whether the file already exists. If it exists, it uses the cache. If it does not exist, babel-core escapes, zlib compression, and fs are written to the cache. It caches according to the file content.It does not affect other loaders.
ignorePlugin and noParse
Ignore unnecessary plugins.For example, if parsing is not required when jquery is introduced, it can be declared in noParse.
module:{
noParse:/jquery/,//不去解析jquery中的依赖库
}happyPack
- js single thread, enable multi-process packaging
- Improve build speed (especially multi-core CPUs)
const HappyPack = require('happypack')
modles:{
rules: [
// js
{
test: /\.js$/,
// 把对 .js 文件的处理转交给 id 为 babel 的 HappyPack 实例
use: ['happypack/loader?id=babel'],
include: srcPath,
// exclude: /node_modules/
}]
}
// plugins中
// happyPack 开启多进程打包
new HappyPack({
// 用唯一的标识符 id 来代表当前的 HappyPack 是用来处理一类特定的文件
id: 'babel',
// 如何处理 .js 文件,用法和 Loader 配置中一样
loaders: ['babel-loader?cacheDirectory']
})ParallelUglifyPlugin
- webpack's built-in Uglify tool compresses js
- js single thread, enabling multi-threading is faster
- Same as happyPack
// 引用
const ParallelUglifyPlugin = require('webpack-parallel-uglify-plugin')
// plugins中配置
// 使用 ParallelUglifyPlugin 并行压缩输出的 JS 代码
new ParallelUglifyPlugin({
// 传递给 UglifyJS 的参数
// (还是使用 UglifyJS 压缩,只不过帮助开启了多进程)
uglifyJS: {
output: {
beautify: false, // 最紧凑的输出
comments: false, // 删除所有的注释
},
compress: {
// 删除所有的 `console` 语句,可以兼容ie浏览器
drop_console: true,
// 内嵌定义了但是只用到一次的变量
collapse_vars: true,
// 提取出出现多次但是没有定义成变量去引用的静态值
reduce_vars: true,
}
}
})About starting multiple processes
If the project is large and packaging is slow, enabling multiple processes can improve the speed.However, if the project is small and the packaging is fast, turning on multiple processes will reduce the speed (process overhead), so use it as needed.
Auto refresh
After modifying the code, the changed code is displayed in the browser. If webpack-dev-server is used, watch will automatically turn on automatic refresh.
watch: true, // 开启监听,默认为 false
watchOptions: {
ignored: /node_modules/, // 忽略哪些
// 监听到变化发生后会等300ms再去执行动作,防止文件更新太快导致重新编译频率太高
// 默认为 300ms
aggregateTimeout: 300,
// 判断文件是否发生变化是通过不停的去询问系统指定文件有没有变化实现的
// 默认每隔1000毫秒询问一次
poll: 1000
}Hot update
Normal refresh, the entire page is refreshed, the speed is relatively slow, and the status will be lost.In the case of hot update, the web page will not be refreshed, the new code will take effect, and the status will not be lost.
// 第一步引入
const HotModuleReplacementPlugin = require('webpack/lib/HotModuleReplacementPlugin');
// 第二步
entry: {
// index: path.join(srcPath, 'index.js'),
index: [
'webpack-dev-server/client?http://localhost:8080/',
'webpack/hot/dev-server',
path.join(srcPath, 'index.js')
]
},
// 第三步 在devServer中设置 开启
hot:trueThe above enables hot update. When modifying the css style, it can be hot updated without refreshing the page. However, modifying the js will still refresh the page.
// // 开启热更新之后的代码逻辑
// if (module.hot) {
// module.hot.accept(['./math'], () => {
// const sumRes = sum(10, 30)
// console.log('sumRes in hot', sumRes)
// })
// }The above means that when the specified math module code is modified, the callback function will be returned and the results will be displayed.Others will refresh the page.
If the page is really complex and has many statuses, hot update can be enabled.
DllPlugin dynamic link library
- Front-end frameworks such as Vue and React are large and slow to build.
- Relatively stable, version upgrades are infrequent
- The same version only needs to be built once and does not need to be built multiple times.
- webpack has built-in DllPlugin support
- (1) DllPlugin --> Package the dll file (prepackage first)
- (2) DllReferencePlugin --> Use dll files (no matter how many changes and upgrades are made, as long as the version is not upgraded and the file remains unchanged, the result will always be used)
TIP
Regardless of whether the dllPlugin is configured or not, it has no impact on the source code of the program.
(1) First configure webpack.dll.js and package the dll file through the dll plug-in
Click to expand the configuration example
const path = require('path')
const DllPlugin = require('webpack/lib/DllPlugin')
const { srcPath, distPath } = require('./paths')
module.exports = {
mode: 'development',
// JS 执行入口文件
entry: {
// 把 React 相关模块的放到一个单独的动态链接库
react: ['react', 'react-dom']
},
output: {
// 输出的动态链接库的文件名称,[name] 代表当前动态链接库的名称,
// 也就是 entry 中配置的 react 和 polyfill
filename: '[name].dll.js',
// 输出的文件都放到 dist 目录下
path: distPath,
// 存放动态链接库的全局变量名称,例如对应 react 来说就是 _dll_react
// 之所以在前面加上 _dll_ 是为了防止全局变量冲突
library: '_dll_[name]', // lib全局变量名
},
plugins: [
// 接入 DllPlugin
new DllPlugin({
// 动态链接库的全局变量名称,需要和 output.library 中保持一致
// 该字段的值也就是输出的 manifest.json 文件 中 name 字段的值
// 例如 react.manifest.json 中就有 "name": "_dll_react"
name: '_dll_[name]',
// 描述动态链接库的 manifest.json 文件输出时的文件名称
path: path.join(distPath, '[name].manifest.json'),
}),
],
}Configure script in package.json.Set "dll": "webpack --config build/webpack.dll.js"
Execute npm run dll
At this time, react.dll.js and react.manifest.json will be generated in dist.
(2) Usage of dll: as follows First, reference the react.dll.js file (the generated js content) in index.html. You can also introduce the file using dynamic tags.
AddAssetHtmlPlugin in the plugin of the dev environment can dynamically insert files into html
new AddAssetHtmlPlugin({ filepath: path.join(distPath, 'react.dll.js'), }),Then configure the manifest address
// 第一,引入 DllReferencePlugin
const DllReferencePlugin = require('webpack/lib/DllReferencePlugin');
module: {
rules: [
{
test: /\.js$/,
loader: ['babel-loader'],
include: srcPath,
exclude: /node_modules/ // 第二,不要再转换 node_modules 的代码
},
]
}
// 第三,在plugins中,告诉 Webpack 使用了哪些动态链接库
new DllReferencePlugin({
// 描述 react 动态链接库的文件内容
manifest: require(path.join(distPath, 'react.manifest.json')),
})webpack optimizes build speed
Which ones are available for production environments?
- Optimizing babel-loader caching can be used in both development and production environments
- IgnorePlugin can avoid the introduction of some modules
- noParse webpack accurately filters files that do not need to be parsed
- happyPack will be faster if it enables multi-process packaging
- parallelUglifyPlugin compression code
- DllPlugin precompiles dependencies and can be used in production builds; load its output correctly and manage versions and caching
What configurations cannot be used in production environments?
- Auto refresh
- Hot update
webpack performance optimization
Goal:
- Smaller size
- Reasonable subcontracting and no repeated loading
- Faster and uses less memory
Practice:
- Small images are base64 encoded and use url-loader to set the limit.
- The hash value is added to the bundle. If the hash of the unchanged file remains unchanged, the cache will be hit when loading.
- Lazy loading, load the basic files first, and large files can be loaded asynchronously
- Extract common code and configure splitChunks in optimization to split code blocks
- ignorePlugin For example: quote the moment library, which contains multiple languages, ignore it, and introduce the required language yourself.
- Use a CDN by setting output publicPath and deploying the assets; the resource-path option used with url-loader is also named publicPath.
- Using Production, the code will be automatically compressed when the mode is set to production.Appeared after webpack4.x.If you feel it is slow, you can use ParallelUglifyPlugin to enable multi-thread compression. If it is already fast according to your own situation, do not add it.When mode=production, vue and react will automatically delete the debugging code (such as the warning in the development environment).Production enables tree-shaking-related optimizations; their effectiveness depends on how well modules can be statically analyzed and how side effects are declared
- Use Scope Hoisting
The difference between es6 module and commonjs
Frontend builds commonly use ES modules; Node.js supports both ES modules and CommonJS.
es6 module is statically introduced and introduced during compilation
commonjs is introduced dynamically and is introduced during execution
The static structure of ES modules enables tree shaking; dynamic CommonJS loading and exports can limit this analysis.
CommonJS
require()returns the value ofmodule.exports, sharing a reference when it is an object; destructured primitive values do not update automatically. ES module named imports are live bindings. Node.js modules.The commonjs module is loaded at runtime, and the es6 module is the compile-time output interface.
CommonJS normally executes a module on first load and caches its result; circular dependencies may receive partially initialized exports.
ES modules establish export bindings during linking and execute code during evaluation; exports can also be accessed through a namespace object.
// commonjs方式引入
let apiList = require('../config/api.js')
if(isDev){
// 可以执行时动态引入
apiList = require('../config/api_dev.js')
}
// es6 module方式引入
import apiList from '../config/api.js'
if(isDev) {
// 编译时报错,因为只能静态引入
import apiList from '../config/api.js'
}tree shaking
A module can have multiple methods. As long as one of the methods is used, the entire file will be put into the bundle. Tree shaking means that only the used methods are put into the bundle and the useless ones will be deleted in the
uglifystage.The principle is to take advantage of the characteristics of the es6 module. It can only appear as a top-level statement of the module. The module name of the import can only be a character constant.
Webpack supports it by default and is enabled by default in production mode.
- "sideEffects": false All code has no side effects (all can perform
tree-shaking)
- "sideEffects": false All code has no side effects (all can perform
CSS and polyfills often have side effects. Declare
"sideEffects": ["*.css", "./src/polyfill.js"]correctly to prevent accidental removal.Tree Shaking.
scope Hosting
Put the content of multiple js into one function, so that the number of scopes is smaller, less memory is consumed, and there is no need to make frequent cross-scope calls.
The principle of scope hositing is to place all modules in a function scope in order of reference, and then rename some variables appropriately to prevent naming conflicts.
This feature is enabled by default when mode is production.The development environment requires the webpack.optimizeModuleConcatenationPlugin plug-in
- Smaller code size
- Create function scopes with less scope
- Code is more readable
Configuration:
const ModuleConcatenationPlugin = require('webpack/lib/optimize/ModuleConcatenatoinPlugin')
module.exports = {
resolve:{
// 针对npm中的第三方模块优先采用jsnext:main中指向的es6 module模块化语法文件
mainFields: ['jsnext:main','browser', 'main']
},
plugins:[
// 开启scope hosting
new ModuleConcatenationPlugin(),
]
}Why package and build
- Smaller size (Tree-shaking, compression, merging), faster loading
- Compile high-level languages or grammars (TS, es6+, modular, scss)
- Compatibility and error prompts (Pollyfill, postcss, eslint)
- Unified and efficient development environment
- Unified build process and output standards
- Integrate company construction specifications (testing, launch, etc.)