1. Use NPM Scripts to manage development commands
- Use
NPM Scripts
to configure the development of command, that ispackage.json
thescripts
field, so even if we modify the script even switchWebpack
to other packaging tool for the rest of the team, using commands remain the same, the proposed commands include:
npm start
: Equivalentnpm run start
, used to develop commands to quickly start local development services;npm run build
: Used for packaging in the production environment;- Other commands, similar
npm run test/lint
, etc., can be added according to the relevant
- In
package.json
usecross-env
to distinguish the environment, a look at the following example:
{
// ...
"scripts": {
"start": "cross-env NODE_ENV=development webpack --config webpack.config.dev.js --mode development",
"build": "cross-env NODE_ENV=production webpack --config webpack.config.prod.js --mode producation",
"analyzer": "cross-env NODE_ENV=production webpack --config webpack.config.analyzer.js --mode producation",
"lint": "lint-staged"
}
// ...
}
Two, Webpack distinguishes multi-environment configuration
- Distinguishing production and development environment configuration, and general packaging configuration, i.e.
Webpack
the configuration file is divided into:
- General arrangement
webpack.config.base.js
; - Development environment configuration
webpack.config.dev.js
; - Production environment configuration
webpack.config.prod.js
;
- webpack.config.base.js
common configurationwebpack.config.base.js
for common configuration, e.g.entry、loader 和 plugin
the like, but some need tocross-env
passNODE_ENV
perform configuration environment variables such as:NODE_ENV=development
the time usedstyle-loader
, andproduction
when usedmini-css-extract-plugin
inloader
the production environmentCSS
generates a separateCSS
file ;
// webpack.config.base.js
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const isProduction = process.env.NODE_ENV === 'production';
module.exports = {
// ...
module: {
rules: [
{
test: /\.css?$/,
use: [
{
loader: isProduction ? MiniCssExtractPlugin.loader : 'style-loader'
},
{
loader: 'css-loader',
options: {
importLoaders: 1,
sourceMap: !isProduction
}
},
{
loader: 'postcss-loader',
options: {
sourceMap: !isProduction
}
}
]
}
]
}
// ...
};
-
webpack.config.dev.js
development environment configurationwebpack.config.dev.js
mainly for the development environment configuration, mainlydevServer
,API mock
and other related configuration, which is part of the configuration focusing on efficiency, speed optimization package is also very important. -
webpack.config.prod.js
webpack.config.prod.js
for production configuration, this part of the line focus is optimal configuration package configuration, comprisingsplitChunks
, resource compression,CDN
path configuration (theoutput
configuration), and other configuration may also be in theterser-webpack-plugin
forced removal of some of the configuration forget Deleted debugging information: for exampledebugger、alert
.
Note that the production environment is not recommended package generation
sourcemap
, if generated and do not upload to the online environment, because ifsourcemap
after on-line, will be equal to others throughChrome
other tools to directly view the source code line, which is very dangerous! But if you use a similar projectSentry
isJavaScript
being given collection and analysis platform, we cansourcemap
go throughWebpack
to generate, remember to delete these files in the package on the line, preventing uploaded to online after uploading to the corresponding platform!
-
webpack.config.analyzer.js
In addition to these three profiles, in order to help us analyze the code package is reasonable to do a split, we can add awebpack.config.analyzer.js
, this configuration is actually inheritedwebpack.config.prod.js
, then addwebpack-bundle-analyzer
the plugin configuration. -
Use
webpack-merge
management configuration file relationships
Webpack
after splitting profile, each have a dependency relationship between the specific relationship is as follows:
webpack.config.dev.js
They are mergedwebpack.config.base.js
and their configuration;webpack.config.prod.js
Mergerwebpack.config.base.js
and their configuration;webpack.config.analyzer.js
Mergerwebpack.config.prod.js
and their configuration, andwebpack.config.prod.js
is fromwebpack.config.base.js
.
- If this configuration to maintain the relationship, then you need to use
webpack-merge
this tool library,webpack-merge
mainly to provide aWebpack
configuration objectMerge
function to merge two configuration, similar to theObject.assign
function of the function. Aswebpack.config.analyzer.js
look atwebpack-merge
how to use:
const merge = require('webpack-merge');
const prodWebpackConfig = require('./webpack.config.prod.js');
const {
BundleAnalyzerPlugin} = require('webpack-bundle-analyzer');
module.exports = merge(prodWebpackConfig, {
// 增加 webpack-bundle-analyzer 配置
plugins: [new BundleAnalyzerPlugin()]
});
3. Reasonable use of split Chunks
- In use
splitChunks
mainly to the size of a reasonable division of resources, improve the cache hit rate, thereby reducing the load time resources on the division of rationality must pay attention to grasp the intensity, too thin can not take advantage ofHTTP Cache
, too thick will lead to slow loading this Degrees are not generally defined, but generally speaking, the code can be split according to the following three principles:
- Frequency of change;
- Page
Router
; - Separation of movement and static.
-
Change the frequency
of code change according to the frequency usedsplitChunks
to split, these are not about to frequent changes of common frameworks and libraries put together as acommon
code, and then the business code split between pages in accordance with the public part and the private part -
After
the framework and library code that the page router does not change frequently are split, the rest is business code. The business code can be split together according to the common code between different pages, so that you can ensure that the framework code and the library code can be combined with one page. The common code is cached in the browser, and access to the second page will not increase the frame code and common code page request. -
Separation of
dynamic and static refers to the fact that(使用import()或者require.ensure())
the module code in the page that is not used frequently or needs to be dynamically and asynchronously loaded can be split into their own separatelychunks
, which ensures the speed of the first screen of the page. Further similarVue、React
such application a single page, the pageRouter
code between are asynchronously loaded, the entire page will be the first entry of the current page and a large frame entered code is loaded, so when the page click jump requires only two dynamic loading the correspondingRouter
code to the.
Four, specify the hash value of the chunk
- Packaged in a production environment, the configuration file must be
filename
thehash
recommendedhash
configuration rules are as follows:
JavaScript
File usage[chunkhash]
:;CSS
File usage[contenthash]
:;- Other static resources used:
[hash]
such as images, fonts, etc., inurl-loader
the configuration[hash]
Five, best practices at the grammatical level
-
The use of
ES6 Modules
grammar, in order to ensure thatTree-Shaking
work. -
Fair use
Ployfill
, it is recommended to use@babel/preset-env
theuseBuiltIns='usage'
program. -
Rational use of
Webpack
magic comments(magic comments)
, such as: use dynamically loaded moduleswebpackChunkName
are named, you can also use significant resourceswebpackPrefetch
ahead of the pre-loaded. -
Use a reasonable version of the framework or class library, for example:
Lodash
Uselodash-es
version and use by the module;Momentjs
Useddate-fns
in place of, and use by the module;- Moving the page using
Zepto
in placejQuery
; Vue、San、React
Choose the right kind of framework library builds the actual situation, in order toVue
, for example, actually builds include browser version,ESM
version,UMD
multiple version, the full version, etc.
Six, other best practices for Webpack configuration
- Production environment using
mini-css-extract-plugin
the exportCSS
documents; - Production environments compression, comprising
JavaScript、CSS、图片、SVG
the like; - The rational allocation of search path, reducing search time, such as setting
alias
, add the path of the project, the investigationnode_modules
to find and so on; - In
rule
the configuration, there aretest、include、exclude
three possible configuration of the control range, best practice:
- Only in
test
and file name matching using regular expressions; - In
include
andexclude
using an absolute path array; - Try to avoid it
exclude
and prefer to use itinclude
.
icon
Image files much useCSS Sprite
to merge pictures, to prevent settingurl-loader
andsvg-url-loader
thelimit
value of unreasonable, resulting inicon
files in aBase64
way the introductionCSS
file, causingCSS
the file is too large.
Seven, other best practices
- Standardized
Git
workflow:
- Use
Git Hook
, similar to theHusky
type ofGit Hook
library that can help us before each submission(pre-commit)
automatically do thelint
checks; - Use
Commitizen
to regulateGit
the submissionCommit Log
;
-
Component-based development, public
UI
assemblies, public library building; here that the more abstract, the need for specific projects to divide, for example, we can be multiple pages commonUI
abstracted components; can also build up a common tool library, similar toLodash
that Class library -
Choose a handy
CSS
pre-languageSass、Less、Stylus
, only the team can easily use; -
Specify rules and conventions, including code specifications, directory structure, document specifications, etc.;
-
Separate front and rear ends, select the appropriate
Mock
program; -
Make best practices into scaffolding for standard projects, and use scaffolding tools to create new projects;
-
Abstract solutions, integrated into the
Webpack
configuration, even based onWebpack
doing their best practices tool chain.