Build projects manually from 0-1 Webpack
1. Install the NPM package
npm install webpack-cli webpack -D
2. Create a configuration file in the specified folder
We can create the corresponding configuration file in the root directory or in the directory we want (eg: /config)
We can write three configuration files to distinguish the environment and so on
# at /config
touch webpack.common.js
touch webpack.dev.js
touch webpack.prod.js
Copy the code
2.5 Configuring all ES Modules (Optional)
Set the property type to module in package.json to specify that all JS files are parsed with es Module.
# package.json
{
"type": "module"
}
Copy the code
Note that __dirname and __filename are not supported if we use es Module. Import.meta. url(the address of the current file) can be used directly, and the URL in the URL module can be used to assemble the desired content, instead of using __dirname, __filename, etc. For example:
import { URL } from 'url'
export default {
entry: {
// index: path.join(__dirname, ".. /src/index.js")
index: new URL('.. /src/index.js'.import.meta.url).pathname,
},
output: {
filename: '[name].[contenthash:4].js'.// path: path.join(__dirname, '.. /dist') // distribution
path: new URL('.. /dist/'.import.meta.url).pathname,
}
}
Copy the code
3. Configure the scripts package
After configuration, we can install the following two toolkits since we need to merge configuration folders and the project may need to be launched on different platforms
npm install webpack-merge cross-env -D
Copy the code
Webpack-merge is used to merge configuration files
Cross-env is used to handle compatibility issues between different platform systems on the command line
4. Generate AN HTML file using the configuration content
Start by installing the HTML-webpack-plugin to handle generating HTML files
npm install html-webpack-plugin -D
At the same time in order to develop debugging can automatically start the server, we can use
npm install webpack-dev-server -D
To deal with local service issues
5. Support front-end frameworks, such as React
Reference the package first
npm install react react-dom -S
Configuring the compilation tool
npm install babel-loader @babel/core @babel/preset-react -D
/ /. Babelrc file
{
"presets": ["@babel/preset-react"] // Preset is the official configured set of plugins, with some options configured
}
Copy the code
// webpack.common.js configuration file
module: {
rules: [{test: /\.(js|jsx)$/,
loader: 'babel-loader'}}]Copy the code
6. Support for ts
npm i @babel/preset-typescript -D
/ /. Babelrc file
{
"presets": ["@babel/preset-react"."@babel/preset-typescript"]// Preset is the official configured set of plugins, with some options configured
}
Copy the code
module: {
rules: [{test: /\.(js|jsx|ts|tsx)$/.// Add ts type support
loader: 'babel-loader'}}]Copy the code
7. Supports CSS and preprocessors
npm i style-loader css-loader sass sass-loader less less-loader
module: {
rules: [{test: /\.(js|jsx|ts|tsx)$/,
loader: 'babel-loader'
},
{
test: /\.css$/,
use:['style-loader'.'css-loader'] {},test: /\.less$/,
use: ['style-loader'.'css-loader'.'less-loader'] and {test: /\.(sass|scss)$/,
use:['style-loader'.'css-loader'.'sass-loader']]}}Copy the code
Note here that if we import one loader, we write lodader directly. If we import more than one loader, we use use, and the loaders in the use array are executed from right to left (similar to popping one loader at a time).
8. Support img introduction, etc
npm install url-loader file-loader -D
module: {
rules: [{test: /\.(js|jsx|ts|tsx)$/,
loader: 'babel-loader'}, {test: /\.css$/,
use: ['style-loader'.'css-loader'],}, {test: /\.less$/,
use: ['style-loader'.'css-loader'.'less-loader'],}, {test: /\.(sass|scss)$/,
use: ['style-loader'.'css-loader'.'sass-loader'],}, {test: /\.(png|jpg|gif|jpeg)$/,
use: [{ loader: 'url-loader'.options: { limit: +10240]}}}, {test: /\.(woff|woff2|eot|ttf|otf)$/, use: 'file-loader'},],}Copy the code
The differences between file-loader and url-loader
File-loader is used to parse images and fonts
Url-loader can also be used to handle images and fonts, and can be set to automatically base64 for smaller resources
9. Support antd
npm install antd -S
If we introduce antd/dist/antd.less, we will get an error. Why is there an error?
Hold your horses, let’s look at the description of the error
This is a reminder that javascript syntax is not supported in less files. We need to startless-loader
Is configured to support JS
{
test: /\.less$/,
use: ['style-loader'.'css-loader', {
loader: 'less-loader'.options: {
lessOptions: {
javascriptEnabled: true,}}}};Copy the code
Answer about javscriptEnabled disprecated
10. Beautify: HereTerminal
Add a progress bar to the compilation process
npm i webpackbar -D
Webpackbar is a plugin that can be used to show compilation and packaging progress.
// webpack.dev.config
plugins: [new Webpackbar()],
Copy the code
webpackbar
11. Optimization
External optimization
The externals configuration option provides the method to “exclude dependencies from the output bundle”. Instead, the bundles created depend on those dependencies that exist in the consumer’s environment. This feature is usually most useful to library developers, but there are a variety of applications that use it.
External prevents packages from being packaged into bundles, and instead obtains these external dependencies at runtime.
We can import react from CDN,react- DOM instead of packaging.
externals: {
// External extension
react: 'React'.'react-dom': 'ReactDOM',},Copy the code
This is a great way to optimize packaging time
external
The stats object
The STATS option gives you more precise control over how bundle information is displayed. The STATS option is a good compromise if you just want to get information about some bundle.
Stats. modules: Tells STATS whether to add information about the build module. The default is true
stats
TerserWebpackPlugin
The plug-in uses Terser to compress JavaScript.
Webpack V5 comes out of the box with the latest version of the Terser-Webpack-plugin. If you are using WebPack V5 or later and want to customize the configuration, you still need to install the Terser-webpack-plugin. If you use Webpack V4, you must install the version of Terser-webpack-Plugin V4.
npm install terser-webpack-plugin esbuild --save-dev
optimization: {
minimizer: [
new TersetWebpackPlugin({
extractComments:false.minify: TersetWebpackPlugin.esbuildMinify / / esbuild sped up}})],Copy the code
TerserWebpackPlugin
css-mini-extract-plugin
This plug-in extracts CSS into a separate file. It creates a CSS file for each JS file that contains CSS. It supports on-demand loading of CSS and Sourcemap. Only supported in WebPack V5 and later.
npm i mini-css-extract-plugin -D
Usage is not described here, just read the documentation
mini-css-extract-plugin
clean-webpack-plugin
A webpack plugin to remove/clean your build folder(s).
const webpackConfig = {
plugins: [
/** * All files inside webpack's output.path directory will be removed once, but the * directory itself will not be. If using webpack 4+'s default configuration, * everything under
/dist/ will be removed. * Use cleanOnceBeforeBuildPatterns to override this behavior. * * During rebuilds, all webpack assets that are not used anymore * will be removed automatically. * * See `Options and Defaults` for information */
new CleanWebpackPlugin(),
],
};
Copy the code
npm i clean-webpack-plugin -D
clean-webpack-plugin
css-minimizer-webpack-plugin
This plugin uses cssnano to optimize and minify your CSS.
npm i css-minimizer-webpack-plugin -D
css-minimizer-webpack-plugin
happyPack
Since JavaScript is a single-threaded model, we can enable the capabilities of multi-core cpus by using multi-processes. The idea of happyPack is to use multiple sub-processes to parse and compile JS, CSS, etc., so that multiple sub-tasks can be processed in parallel, and the results of each sub-task can be sent to the main process
npm install happypack -D
1. Create the happypack plug-in instance
// webpack.common.js
// import HappyPack from 'happypack'
// import os from 'os'
// const happyThreadPool = HappyPack.ThreadPool({ size: os.cpus().length})
plugins: [
new HappyPack({
id: 'babel'.// Uniquely identifies the current instance, which will be used later in module/rules
loaders: ['babel-loader? cacheDirectory'].// Same as Loader in module/rules
threads: 3.// Indicates the number of child processes to process this type of file. The default number is 3. The type must be an integer.
threadPool: happyThreadPool, // // uses child processes in the shared process pool to process tasks}),].Copy the code
2. Use in Loder
module.exports = {
module: {
rules: [{test: /\.(js|jsx|ts|tsx)$/.// loader: 'babel-loader',
// In the Loader configuration, all files are handled by happypack/ Loader, using the queryString that follows. Id = Babel tells happypack/loader to select which instance of happypack to process files.
use: ['happypack/loader? id=babel'].exclude: /node_modules/,},]},}Copy the code
happypack
-
TODO: Follow-up updates, welcome to leave a message to ask, urge more
eslint
CI/CD
The pre commit to check