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

  1. Install webpack

    npm i webpack webpack-cli -D

    npm i webpack-merge -D

  2. Configure the Webpack file

    1. 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
    2. Create environment variable files

      config/process.env.js

    3. 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.

  1. Module. noParse prevents precompilation of matching rules

    noParse: RegExp | [RegExp] | function

  2. 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.

  3. 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

  4. 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

  5. rule.oneOf

    Receiving an array, the file resource by default finds the first matching rule in oneOf to invoke the corresponding loader processing.

  6. rule.parser

    Parse the option object. Parsing options for all applications are merged.

  7. rule.use

    UseEntries list applied to modules. Specify one loader for each entry.

  8. 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.

  1. loader

    This parameter is used to define a specific loader, which is equivalent to: use:[loader].

  2. 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.

  1. 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

  2. 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.

  3. @babel/preset-env

    Represents compiling JavaScript ES6 syntax code into ES5 syntax

  4. @babel/preset-react

    Represents compiling JSX and other things into JavaScript

  5. @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

  6. 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

  7. @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
  8. @babel/plugin-proposal-class-properties

    // Compile and parse the arrow function in the class

    npm i @babel/plugin-proposal-class-properties -D

  9. @babel/plugin-syntax-dynamic-import

    // compile and parse dynamically imported resources

5. Loader loads resources

  1. Deal with CSS loader

    1. Load resources

      npm i style-loader css-loader sass-loader node-sass -D

    2. 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
  2. Add the WebPack loader configuration

    Configuration webpack module. Rules

  3. Handle image, font, file loader

    1. Load resources

      npm i file-loader -D

    2. Add the WebPack loader configuration

    Configuration webpack module. Rules

  4. 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

  1. Add HtmlWebpackPlugin,

    // Add to webpack plugins to dynamically package output HTML files

    npm i html-webpack-plugin -D

  2. 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

  1. The installation

    npm i webpack-dev-server -D

  2. Configure the WebPack configuration file devServer

  3. Add module hot update plugins

    new webpack.NamedModulesPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    Copy the code

8. Configure webPack Resolve

  1. 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.

  2. resolve.alias

    Set an alias that references the file path

  3. resolve.extensions

    Automatically resolve the identified extensions.

9. Other WebPack configurations

  1. Tell Webpack to specify an environment for the target

    target: 'web',

  2. Instead of packing imported packages into the bundle, obtain these external dependencies at runtime.

    externals: {
      jquery: 'jQuery',},Copy the code
  3. How does the configuration display performance prompts

    MaxAssetSize: 1024 * 500,},Copy the code

10. Pack, separate and compress

  1. 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
  2. To prevent the repeat

    new webpack.optimize.CommonsChunkPlugin({
      name: 'common'// Specify the name of the public bundle. })Copy the code
  3. 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

  1. The installation

    npm i react-router react-router-dom -S

  2. Create the routes configuration file

  3. Add the route configuration method routes/index.js

  4. Create the route object routes/method/dynamic-loader.js

  5. Directions for use

    1. Page routing must be written under modules/ modules
    2. 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

  1. The installation

    npm i redux redux-logger redux-saga reselect -S

  2. Middleware redux-Logger prints redux and new logs

  3. The middleware Redux-Saga handles side effects operations

  4. Reselect calculates derived data

  5. Directions for use

    1. The Reducer file must be used in themodules/Module, and the file namereducer
    2. Saga files must be used inmodules/Module, and the file namesaga

4. Install axiOS API requests

  1. configurationrequest.jsRequest module

Eslint configuration

  1. The installation

    npm i eslint -D

  2. Create base.eslintrc.js

    , / node_modules/bin/eslint - - init

  3. Install Babel – eslint

    Added ES2015 language specification support

    npm i babel-eslint -D

    Add it in the.eslintrc.js configuration

    "parser":"babel-eslint"

  4. 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
  5. Modify the.eslintrc.js configuration

    "extends":"airbnb",

  6. 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.