Use webpack to build your own react scaffold from 0

Time:2020-11-22

react-cli-diy

Use webpack to build your own react scaffold from 0

Source code address

Project use:

git clone [email protected]:TigerHee/react-cli-diy.git

cd react-cli-diy

npm install

Start of development mode:
npm run dev

Production packaging:
npm run build

Implementation steps:

First, create a new project directory and execute it in this directorynpm initInitialize the project environment.

To create a webpack configuration file:

  • webpack.config.js //Public configuration
  • webpack.prod.js //Production environment configuration
  • webpack.dev.js //Development environment configuration

Create a public directory to store HTML template files.

Create the SRC directory to store the resources required by the front-end project.

To install webpack related dependencies:

npm i webpack webpack-cli webpack-merge -D

modify webpack.config.js Document:

module.exports = {
  entry: './src/ index.js "// entrance
  Output: {// export
    filename: 'bundle.[hash:8].js',
    path: path.resolve(__dirname, 'dist')
  },
}

Use the webpack merge package to merge the common configuration file to the production and development configuration files respectively

const merge = require('webpack-merge')
const baseConfig = require('./webpack.config.js')

module.exports = merge(baseConfig, {
  //Separate configuration
})

To install local services and use HTML template related dependencies:

npm i webpack-dev-server html-webpack-plugin -D

Use in public configurationhtml-webpack-pluginTo use index.html Template:

plugins: [
  new HtmlWebpackPlugin({
    template: './public/index.html',
    filename: 'index.html',
    Hash: true, // add hash value to solve cache problem
    Minify: {// compress the packaged HTML template
      Removeattributequotes: true, // delete attribute double quotes
      // collapse whitespace
    }
  }),
]

The development mode needs to use the development server:

Devserver: {// built in development server configuration
  port: 3000,
  progress: true,
  contentBase: './dist',
  open: true,
  proxy: {
    //Setting development time interface proxy address
  }
},

After the basic configuration of appeal is configured, thepackage.jsonInternal setting startup script:

"scripts": {
  "build": "webpack  --config webpack.prod.js",
  "dev": "webpack-dev-server --config webpack.dev.js"
},

Next, set CSS and less in the public configuration

rules:[
  {
    test: /\.(css|less)$/,
    use: [
      'style-loader',
      'css-loader',
      'postcss-loader',
      'less-loader'
    ]
  },
]

A separate configuration file is required for postcss loader to handle compatible prefixes postcss.config.js 。

If CSS is processed in the above configuration, the style file is inserted into the HTML template. We want to extract the CSS file and import it through the link mode

npm i mini-css-extract-plugin -D

const MiniCssExtractPlugin = require('mini-css-extract-plugin');

{
  module:{
    rules: [
      {
        test: /\.(css|less)$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          'postcss-loader',
          'less-loader'
        ]
      },
    ]
  },
  plugins: [
    //Pull out CSS plug-in
    new MiniCssExtractPlugin({
      filename: '[name].[hash:8].css',
      chunkFilename: '[id].[hash:8].css',
    }),
  ]
}

At this time, thenpm run buildIt is found that the last packing result of each packing is deposited, which needs to be removed first:

npm i clean-webpack-plugin -D

Modify production environment configuration:

const { CleanWebpackPlugin } = require('clean-webpack-plugin');

plugins:[
  //Delete empty dist before each package
  new CleanWebpackPlugin(),
]

Yesmini-css-extract-pluginTo extract CSS as link, you need to useoptimize-css-assets-webpack-pluginUse this method to compress the CSSuglifyjs-webpack-pluginCompression JS:

npm i optimize-css-assets-webpack-plugin uglifyjs-webpack-plugin -D

Optimization: {// optimization item
  minimizer: [
    New uglifyjsplugin ({// optimize JS)
      Cache: true, // whether to cache
      Parallel: true, // whether to package concurrently
    }),
    New optimizecss assetsplugin ({}) // optimization of CSS
  ]
},

Set JS and JSX in the public configuration

npm i babel-loader @babel/core @babel/preset-env @babel/plugin-proposal-class-properties @babel/plugin-proposal-decorators -D

In addition, Babel of react:

npm i @babel/preset-react -D

{
  test: /\.(js|jsx)$/,
  use: {
    loader: 'babel-loader',
    options: {
      presets: [
        '@babel/preset-env',
        '@babel/preset-react'
      ],
      plugins: [
        ["@babel/plugin-proposal-decorators", { "legacy": true }],
        ["@babel/plugin-proposal-class-properties", { "loose": true }]
      ]
    }
  },
  exclude: /node_modules/
},

Add related projects:

npm i react react-dom -S

stay index.js Write react code inside, um ~ ~ ~, can run.

Then add image processing in the public configuration:

npm i file-loader url-loader -D

{
  test: /\.(png|jpg|gif)$/,
  use: {
    loader: 'url-loader',
    options: {
      Limit: 200 * 1024, // less than 200K becomes Base64
    }
  }
}

Try adding a background image in less, OK.

Development mode needs to monitor the hot update of changes:

watch: true,
watchOptions: {
  Poll: 1000, // listen 1000 times per second
  Aggregatetimeout: 300, // anti shake. When the first file is changed, the delay will be increased before rebuilding
  ignored: /node_ Modules // / can exclude some huge folders,
},

lastnpm run buildandnpm run devThe scaffold is successfully constructed.

Recommended Today

Explain module, import and export in JavaScript

Author: Tania rascia Crazy technology house Original text:https://www.taniarascia.com/j… In the era of the Internet, websites are mainly developed with HTML and CSS. If you load JavaScript into a page, it usually provides effects and interactions in the form of small fragments. Generally, all JavaScript code is written in a file and loaded into a filescriptTag. […]