preface
React framework is based on WebPack 4.0, which contains common configuration of projects. It is packaged, compressed, and optimized for rapid development.
The directory structure
| -- - build webpack configuration file | -- - config/profile | -- - | dist/project packaging file - - node_modules/third party modules | -- - | -- - SRC/public/HTML template Project directory | | -- - | common/public module | -- - | components/public component module | -- - modules/page module | | -- - | routes/routing configuration module | -- - store / Redux configuration module | | - styles/global stylesheet module | | -- - | util/global method module | -- - index. | -- - js entry pagetest/ test code module | -- -. Babelrc webpack Babel configuration file | -- -. Gitignore git code management configuration module | -- -. Eslintrc. Js eslint configuration file | -- -- package. Json Package management | -- - README. Md fileCopy the code
Webpack configuration
1. The webpack configuration
-
Install webpack
npm i webpack webpack-cli -D
npm i webpack-merge -D
-
Configure the Webpack file
-
Create a Webpack file
// Public webpack file build/webpack.base.js // development environment webpack file build/webpack.dev.js // production environment webpack file build/webpack.prod.js // Test the environment webpack file build/webpack.stag.jsCopy the code
-
Create environment variable files
config/process.env.js
-
Run the webpack command
// Add execution commands to scripts in package.json
"scripts": { "dev": "webpack-dev-server --config build/webpack.dev.js --progress --colors"."build:prod": "webpack --config build/webpack.prod.js --progress --colors"."build:stage": "webpack --config build/webpack.prod.js --progress --colors",}Copy the code
// Run NPM run dev
// Package production environment NPM run build:prod
// Package test environment NPM run build:stage
-
2. The module (module)
The Module option basically sets the loaders used in WebPack. Use rules to match application-specific files with loaders or modify parsers.
-
Module. noParse prevents precompilation of matching rules
noParse: RegExp | [RegExp] | function
-
Module. rules Sets matching rules
The module.rules option specifically sets rules for loaders to match files.
module.rules: [{...}]
Each object in rules determines the specific type of loaders and the specific file that loders work on.
-
File matching
rule.test, rule.exclude, rule.include, rule.and, rule.or, rule.not
The above three objects are actually mounted to the rule-resource object. You can write directly to the rule or rule-resource object. They have the same value condition.
rule.resourceQuery
-
Condition condition
It is used to set the rule for matching files. Acceptable values are:
condition: string | RegExp | function | array | object
String: indicates the absolute path of the matching file
RegExp: Regex for matching files
Function: path with input, depending on the returned Boolean
Array: Multiple condition matching rules can be passed
Object: not commonly used, used to match keys
-
rule.oneOf
Receiving an array, the file resource by default finds the first matching rule in oneOf to invoke the corresponding loader processing.
-
rule.parser
Parse the option object. Parsing options for all applications are merged.
-
rule.use
UseEntries list applied to modules. Specify one loader for each entry.
-
UseEntries
One of the Loader attributes must be strings. It uses the Loader resolution option (resolveLoader) to resolve relative to the context in the configuration.
You can have an options property as a string or object. The value can be passed to the loader to interpret the options option.
3. Loader Compiler Settings
In Webpack2, the main notation is based on loaders and loaders. However, in WebPack 3 loader loads are determined by file instead. The most notable feature of this is the replacement of loaders with rules.
According to the specification, use is a label used to import time into the Loader. In the WebPack 3 era, the Loader field was retained and the Query field was abolished, but its replacement can be found in use.
-
loader
This parameter is used to define a specific loader, which is equivalent to: use:[loader].
-
query
Used to specify the configuration parameters used by a specific loader, for example
test: /\.js$/, loader: 'babel-loader', query: { presets: ['es2015']}Copy the code
However, query has been deprecated in WebPack 3, using the options option in Use:
test: /\.js$/, use: [ { loader: 'babel-loader', options: { presets: ['es2015']}}]Copy the code
4. Babel configuration
Babel is a JavaScript““ compiler that parses ES6 syntax or es7 syntax resolver, allowing developers to use the new ES syntax and support JSX, TSX, Vue, and other frameworks.
-
Install Babel
// Load the ES2015+ code and use Babel to translate to ES5 NPM i@babel /core babel-loader -d
// Load TypeScript 2.0+ NPM I ts-loader -d or NPM I awesome-typescript-loader -d as JavaScript
-
Configure the Babel file:.babelrc or configure it in babel-loader options
{ "presets": [ "@babel/preset-env"."@babel/preset-react"."state-0"]."plugins": []}Copy the code
Babel supports custom presets or plugins, which are required for Babel to work. It is pointless to install Babel separately.
Presets: on behalf of Babel support the syntax (that is, you write in the syntax), priority is from down to up, the state | 1 | 2 | 0.. Stands for a lot of syntax that is not included in the standard
Plugins: which plugins to use when parsing Babel, similar to presets““, from top to bottom.
-
@babel/preset-env
Represents compiling JavaScript ES6 syntax code into ES5 syntax
-
@babel/preset-react
Represents compiling JSX and other things into JavaScript
-
@babel/plugin-transform-runtime @babel/runtime
Babel uses very small helper code for some public methods, such as _extend. By default, it is added to every file that needs it
You can introduce Babel Runtime as a separate module to avoid duplication.
The following configuration disables automatic runtime injection by Babel for each file, instead introducing @babel/ plugin-transform-Runtime and having all auxiliary code referenced from there.
npm i @babel/runtime @babel/plugin-transform-runtime -D
-
babel-polyfill
The Babel we used earlier, babel-loader, only converts the new JavaScript syntax by default, not the new API. For example, global objects such as Iterator, Generator, Set, Maps, Proxy, Reflect, Symbol, Promise, and some methods defined on global objects (such as Object.assign) do not translate. If you want to use these new objects and methods, you must use Babel-Polyfill to provide a shim for the current environment.
npm i babel-polyfill -D
-
@babel/plugin-proposal-object-rest-spread
Compile and parse… Object syntax
let{ x, y, ... z } = { x: 1, y: 2, a: 3, b: 4 }; console.log(x); // 1 console.log(y); // 2 console.log(z); // { a: 3, b: 4 }Copy the code
-
@babel/plugin-proposal-class-properties
// Compile and parse the arrow function in the class
npm i @babel/plugin-proposal-class-properties -D
-
@babel/plugin-syntax-dynamic-import
// compile and parse dynamically imported resources
5. Loader loads resources
-
Deal with CSS loader
-
Load resources
npm i style-loader css-loader sass-loader node-sass -D
-
Add CSS packaging, separation, compression and deweighting
npm i mini-css-extract-plugin optimize-css-assets-webpack-plugin postcss-loader autoprefixer postcss-import cssnano -D // Add extract CSS plug-in // configure CSS loader, // Optimization. Minimizer add plugin NPM I. // Optimization. Minimizer add plugin NPM I. // Optimization Optimize -css-assets-webpack-plugin -d NPM I postcss-loader -d Compatible with different browser plug-ins NPM I autoprefixer -d // Add @import for CSS. Only local import is supported. Remote URL link processing such as HTTP is not supported Add optimization-csS-assets-webpack-plugin add optimization.minimizer configuration NPM I cssnano -dCopy the code
-
-
Add the WebPack loader configuration
Configuration webpack module. Rules
-
Handle image, font, file loader
-
Load resources
npm i file-loader -D
-
Add the WebPack loader configuration
Configuration webpack module. Rules
-
-
Loading resource data (Optional)
Useful resources to load are also data, such as JSON files, CSV, TSV, and XML. Similar to NodeJS, JSON support is actually built in and can be used directly. NPM install –save-dev Csv-loader XMl-loader is required to import CSV, TSV, and XML
6. Manage output
-
Add HtmlWebpackPlugin,
// Add to webpack plugins to dynamically package output HTML files
npm i html-webpack-plugin -D
-
Add the CleanWebpackPlugin to the clean /dist folder
// Add to webpack Plugins to dynamically clean up the contents of packed files
npm i clean-webpack-plugin -D
7. Use webpack-dev-server to configure the development environment
-
The installation
npm i webpack-dev-server -D
-
Configure the WebPack configuration file devServer
-
Add module hot update plugins
new webpack.NamedModulesPlugin(), new webpack.HotModuleReplacementPlugin(), Copy the code
8. Configure webPack Resolve
-
resolve.modules
Tells WebPack which directory to search for when parsing modules.
Both absolute and relative paths can be used, but be aware that there is a slight difference between them.
-
resolve.alias
Set an alias that references the file path
-
resolve.extensions
Automatically resolve the identified extensions.
9. Other WebPack configurations
-
Tell Webpack to specify an environment for the target
target: 'web',
-
Instead of packing imported packages into the bundle, obtain these external dependencies at runtime.
externals: { jquery: 'jQuery',},Copy the code
-
How does the configuration display performance prompts
MaxAssetSize: 1024 * 500,},Copy the code
10. Pack, separate and compress
-
The compression
npm i terser-webpack-plugin -D
new TerserPlugin({ terserOptions: { compress: { warnings: false, drop_console: true, // console drop_debugger: false, pure_funcs: ['console.log'}, // remove console},},sourceMap: false, parallel: true,}).Copy the code
-
To prevent the repeat
new webpack.optimize.CommonsChunkPlugin({ name: 'common'// Specify the name of the public bundle. })Copy the code
-
The separation
Configuration webpack optimization. SplitChunks
11. Add an offline server
npm i http-server -D
The React configuration
1. Install the React
npm i react react-dom -S
2. Install the React route
-
The installation
npm i react-router react-router-dom -S
-
Create the routes configuration file
-
Add the route configuration method routes/index.js
-
Create the route object routes/method/dynamic-loader.js
-
Directions for use
- Page routing must be written under modules/ modules
- If the page is to become a primary route, you need to add route.js to create a submodule route object
3. Install the react – story
-
The installation
npm i redux redux-logger redux-saga reselect -S
-
Middleware redux-Logger prints redux and new logs
-
The middleware Redux-Saga handles side effects operations
-
Reselect calculates derived data
-
Directions for use
- The Reducer file must be used in the
modules/
Module, and the file namereducer
- Saga files must be used in
modules/
Module, and the file namesaga
- The Reducer file must be used in the
4. Install axiOS API requests
- configuration
request.js
Request module
Eslint configuration
-
The installation
npm i eslint -D
-
Create base.eslintrc.js
, / node_modules/bin/eslint - - init
-
Install Babel – eslint
Added ES2015 language specification support
npm i babel-eslint -D
Add it in the.eslintrc.js configuration
"parser":"babel-eslint"
-
Installing dependency packages
npm i eslint-config-airbnb eslint-plugin-import eslint-plugin-react eslint-plugin-jsx-a11y -D eslint-config-airbnb : Eslint-plugin-import: when using imports, eslint-plugin-react rules are specified: Some react ESLint rules specify eslint-plugin-jSx-a11Y: Some JSX rules specificationsCopy the code
-
Modify the.eslintrc.js configuration
"extends":"airbnb",
-
Let’s add some rules
conclusion
This document mainly introduces some use of the Webpack API, if you want to know “” Webpack” “view a little experience with Webpack to build a front-end project to know more.