Build a WebPack-React project from scratch, basic configuration

Reference links:www.jianshu.com/p/0e01ca947…

1. Initialize an NPM project

npm init
Copy the code

You can change it according to your own needs, or you can go all the way to next. Expected result: a package.json file is generated under the folder

2. Add webpack and write webpack.config.js

npm install webpack
Copy the code

I have installed version 5.61.0 here, which is also ok

npm install webpack@5.61.0
Copy the code

Generate a webpack.config.js file under the folder

const path = require('path');
module.exports = {
  entry: './src/app.js'.output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'app.js'}};Copy the code
  • Entry: address of the js file
  • Output: Sets the package file and package folder
    • Filename: packages a file
    • Path: package path and folder name

New SRC/app. Js

console.log('hello world')
Copy the code

3. Run the following command to pack the package

node_modules/.bin/webpack
Copy the code

Expect the result: a dist folder is generated and app.js is packaged inside it

4. Configuration index. HTML

Installing a plug-in

npm install html-webpack-plugin
Copy the code

Webpack. Config. Js configuration

// Import used to configure index.html
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
  plugins: [
    new HtmlWebpackPlugin({
        template: './public/index.html' //* Configure the index mapping path}})];Copy the code
  • Plugins: Used to set up plug-ins

Expect results using the above package statement: index.html appears in the dist folder and app.js is automatically imported into app.js

5. Parse the ES6 script

Install the compiler

npm install babel-loader@7.12. babel-core@6.26. 0 babel-preset-env@1.61. --dev
Copy the code
module.exports = {
  rules: [//* Configure the resolution rule
    {
      test: /\.js$/.//* Configures the file name extension to resolve
      exclude: /(node_modules)/.//* Do not do folder processing
      use: { //* The parsed module to be applied can be an array, the value can be module name string, module object
        loader: 'babel-loader'.//* Use babel-loader to compile */
        options: { //* Can be a string or object, depending on the situation, and the value will be passed to the loader
          presets: ['env'] //* Select the compiler to use}}}]}Copy the code
  • Rules: Configures resolution rules
    • Test: indicates the file suffix to be parsed
    • Exclude: excludes the compiled folder folder that is not processed
    • Use: The parse module of the application, which can be an array of values as module name strings, module objects
    • Loader: indicates the name of the used compiler
    • Options: a string or object, depending on the specific value, that is passed to the Loader

6. Parse the React

The installation

npm install babel-preset-react
npm install react react-dom
Copy the code

Configure the parser for JSX

rules: [
  {
    test: /\.jsx$/,
    exclude: /(node_modules)/.// Do nothing about this
    use: {
      loader: 'babel-loader'.options: {
        presets: ['env'.'react']    // In the React environment, it can also be packaged}}}]Copy the code

At this point, there are three steps \

  1. Change the entry file to main.js and use the previous app.js as the root component, similar to Vue
  2. Render app.js in main.js
  3. Add a react container to index.html

Change the entry file to main.js and use the previous app.js as the root component, similar to Vue

  • webpack.config.js
entry: './src/main.js'.//* Configure the entry file
Copy the code

app.jsx

const App = () = > {
    return (<div>hello world</div>)}export default App
Copy the code

Render app.js in main.js

  • main.js
import React from 'react'
import ReactDom from './react-dom'

import App from './app'

ReactDom.render(<App />.document.getElementById('root')) //* Parse App to page root
Copy the code

Add a react container to index.html

  • index.html
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Webpack-React</title>
</head>
<body>
    <div id="root"></div>
</body>
</html>
Copy the code

7. Parse the CSS

The installation

npm install style-loader css-loader
Copy the code

webpack.config.js rules

{
  test: /\.css$/,
  use: [ 'style-loader'.'css-loader']}Copy the code

If you just configure the CSS, go to this step. However, the React CSS will be compiled to JS, so the ExtractTextWebpackPlugin todo test is also required

npm install extract-text-webpack-plugin
Copy the code

webpack.config.js

const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin')  //* Parse CSS to js
// rules override
{
  test: /\.css$/,
  use: ExtractTextWebpackPlugin.extract({
    fallback: "style-loader".use: "css-loader"})}Copy the code

Analytical SCSS. 8

Installation:

npm install sass-loader@6.06. node-sass@4.72. --dev
Copy the code

Can’t find python executable “python”, you Can set the Python env variable

  • Python2.7 is required on your computer

www.python.org/downloads/r… Look for the Windows x86-64 MSI Installer version below and install next

  • Configure python environment variables

D: \ data \ env \ python2.7 D: \ data \ env \ python2.7 \ Scripts

// CMD administrator runs the command line interface
npm install gulp-load-plugins --save
npm install --global --production windows-build-tools
Copy the code

If this does not work, use CNPM to install

npm install -g cnpm --registry=https://registry.npm.taobao.org
cnpm install node-sass --save
Copy the code

If that still doesn’t work, specify the version directly in package.json

"sass-loader": "^ 7.1.0"."node-sass": "^ 4.14.1." "
Copy the code

Install again

  • webpack.config.js rules
{
  test: /\.scss$/,
  use: ExtractTextWebpackPlugin.extract({
    fallback: 'style-loader'.use: ['css-loader'.'sass-loader']})}Copy the code

9. Manipulating images

The installation

npm install file-loader@1.16. url-loader@0.62. --dev
Copy the code

webpack.confis.js rules

{
  test: /\.(png|jpg|gif)$/,
  use: [
    {
      loader: 'url-loader'.options: {
        limit: 8192}}}]Copy the code

10. Introduce font ICONS

The installation

npm install font-awesome
Copy the code

webpack.config.js rules

{
  test: /\.(woff|woff2|eot|ttf|otf|svg)$/,
  use: [
    {
      loader: 'url-loader'.options: {
        limit: 8192}}}]Copy the code

11. Extract common modules

Webpack.config. js -> plugins todo to be tested

const webpack = require('webpack')
new webpack.optimize.CommonsChunkPlugin({ //* Extract the public module
  name: "common".// Public module name
  filename: "js/base.js".// Package directory
}),
Copy the code

12. Install webpack-dev-server for running

npm install webpack-dev-server
Copy the code

Configure webpack.config.js -> devServer

DevServer: {port: 8788 // Running port}Copy the code

Add publicPath

output: {
  //* Configures the packaged information
  path: path.resolve(__dirname, "dist"), //* The packaged path
  filename: "app.js".//* Pack the entry file
  publicPath: '/dist/'
},
Copy the code
Webpack dev – server configuration

Command line configuration: The configuration can be changed directly after the command line or in devServer

  • – Watch: dynamically monitors file changes and packages files in real time
  • – hot: thermal load
  • -open: indicates whether to open the browser automatically after compiling
  • –config: Select the webpack.config.js file to use for compilation
Use and start

Webpack. Config. Js configuration

entry: "./src/main.js".//* Configure the entry file
output: {
  //* Configures the packaged information
  path: path.resolve(__dirname, "dist"), //* The packaged path
  filename: "app.js".//* Pack the entry file
  publicPath: '/dist/'
},
Copy the code

Index.html Settings

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Webpack-React</title>
    <! App.js is not displayed unless it is introduced -->
</head>
<body>
    <div id="root"></div>
    <script src="dist/app.js"></script>
</body>
</html>
Copy the code

With publicPath, the import path of script is dist/app.js, or app.js \ if not

[React Error]: Target container is not a DOM element

If this is a problem with publicPath, note that script is not introduced in the head. The dom cannot be found because script was introduced before the DOM was updated

React is not defined

Register React with Windows in main.js

import React from 'react'
window.React = React
Copy the code

//todo

  1. Set the public folder
  2. @ Path Setting
  3. SplitChunks code cutting
  4. Multi-environment webpack.confis.js configuration

Example: Start the command to add a configuration file

{
  "scripts": {
     "start": "webpack-dev-server --open --config webpack.dev.js",
     "build": "webpack --config webpack.prod.js"
  }
}
Copy the code

The webpack.common.js common configuration is up to you to write webpack.dev.js

const merge = require('webpack-merge');
const common = require('./webpack.common.js');

module.exports = merge(common, {
    mode: 'development'.devtool: 'inline-source-map'.devServer: {
        contentBase: './dist'.port: 4001.hot: true}});Copy the code

In the end

const path = require("path");
// Import used to configure index.html
const HtmlWebpackPlugin = require("html-webpack-plugin"); / / * analytical index in HTML
const ExtractTextWebpackPlugin = require("extract-text-webpack-plugin"); //* Parse CSS to js
module.exports = {
  entry: "./src/main.js".//* Configure the entry file
  mode: 'development'.// Set the mode environment
  output: {
    //* Configures the packaged information
    path: path.resolve(__dirname, "dist"), //* The packaged path
    filename: "app.js".//* Pack the entry file
    publicPath: '/dist/'
  },
  devServer: {
    open: false.//* Whether to open the browser automatically after compiling
    port: 8788 // Running port
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "./public/index.html".//* Configure the index mapping path
      filename: 'index.html'//* Specify the name of the generated file})].module: {
    rules: [
      //* Configure the resolution rule
      {
        test: /\.js$/.//* Configures the file name extension to resolve
        exclude: /(node_modules)/.//* Do not do folder processing
        use: {
          //* The parsed module to be applied can be an array, the value can be module name string, module object
          loader: "babel-loader".//* Use babel-loader to compile */
          options: {
            //* Can be a string or object, depending on the situation, and the value will be passed to the loader
            presets: ["env"."react"]./ / * environment}},}, {test: /\.jsx$/,
        exclude: /(node_modules)/.// Do nothing about this
        use: {
          loader: "babel-loader".options: {
            presets: ["env"."react"].// In the React environment, it can also be packaged}},}, {test: /\.css$/,
        use: ExtractTextWebpackPlugin.extract({
          fallback: "style-loader".use: "css-loader",}, {})test: /\.scss$/,
        use: ExtractTextWebpackPlugin.extract({
          fallback: "style-loader".use: ["css-loader"."sass-loader"],})}, {test: /\.(png|jpg|gif)$/,
        use: [
          {
            loader: "url-loader".options: {
              limit: 8192,},},],}, {test: /\.(woff|woff2|eot|ttf|otf|svg)$/,
        use: [
          {
            loader: "url-loader".options: {
              limit: 8192,},},],},},};Copy the code

package.json

{
  "name": "webpack-react"."version": "1.0.0"."description": "Webpack-react project built from scratch"."main": "main.js"."scripts": {
    "dev": "node_modules/.bin/webpack-dev-server --mode development"."webpack-dev": "node_modules/.bin/webpack --mode development"."test": "echo \"Error: no test specified\" && exit 1"."build": "node_modules/.bin/webpack"
  },
  "author": "q"."license": "ISC"."dependencies": {
    "babel-core": "^ 6.26.0"."babel-loader": "^ 7.1.2." "."babel-preset-env": "^ 1.6.1." "."babel-preset-react": "^ 6.24.1"."css-loader": "^ 6.5.1." "."extract-text-webpack-plugin": "^ 3.0.2." "."file-loader": "^ 1.1.6." "."font-awesome": "^ 4.7.0"."gulp-load-plugins": "^ 2.0.7." "."html-webpack-plugin": "^ 5.5.0"."node-sass": "^ 4.14.1." "."react": "^ 17.0.2"."react-dom": "^ 17.0.2"."sass-loader": "^ 7.1.0"."style-loader": "^ 3.3.1"."url-loader": "^ 0.6.2"."webpack": "^ 5.61.0"."webpack-dev-server": "^ 4.4.0"
  },
  "devDependencies": {
    "webpack-cli": "^ 4.9.1." "}}Copy the code