🌝

React+Webpack Scaffold

Posted at — Dec 28, 2020
#react

Create the react+webpack scaffold.

安装webpack

1
2
3
4
5
6
npm init -y
npm i react -S
npm i react-dom -S
npm i webpack -D
npm i webpack-cli -D
npm i babel-loader @babel/core @babel/preset-env @babel/preset-react -D (react打包器)npm i css-loader style-loader -D (css打包器)npm i sass-loader node-sass -D (scss打包器)npm i mini-css-extract-plugin -D (css提取器)npm i html-webpack-plugin -D (复制index.html到dist文件夹的插件)npm i webpack-dev-server -D (webpack-dev-server)

创建src/index.jsx,src/dev.jsx文件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// index.jsx
import React from 'react'
import ReactDOM from 'react-dom'

ReactDOM.render(
    <div>hello  webpack !!!</div>
    , document.getElementById("root"))

// dev.jsx(用于触发HMR)
if (module.hot) {
    module.hot.accept(err => {
        if (err) {
            console.error('Cannot apply HMR update.', err);
        }
    });
}

创建public/index.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>webpack练习</title>
</head>
<body>
    <div id="root"></div>
</body>
</html>

创建并配置webpack.config.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const path = require('path');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin  = require("mini-css-extract-plugin");
const webpack = require('webpack'); //增加导入webpack
module.exports = {
    mode: 'development',
    devtool: 'cheap-module-source-map',
    devServer: {
        hot: true, //在devServer中增加hot字段
        contentBase: path.join(__dirname, './src/'),
        publicPath: '/',
        host: '127.0.0.1',
        port: 3000,
        stats: {
            colors: true
        }
    },
    entry:['./src/index.js', './src/dev.jsx'], //在entry字段中添加触发文件配置
    resolve: {
        extensions: ['.wasm', '.mjs', '.js', '.json', '.jsx']
    },
    module: {
        rules: [
            {
                test: /\.jsx?$/, // jsx/js文件的正则
                exclude: /node_modules/, // 排除 node_modules 文件夹
                use: {
                    // loader 是 babel
                    loader: 'babel-loader',
                    options: {
                        // babel 转义的配置选项
                        babelrc: false,
                        presets: [
                            // 添加 preset-react
                            require.resolve('@babel/preset-react'),
                            [require.resolve('@babel/preset-env'), {modules: false}]
                        ],
                        cacheDirectory: true
                    }
                }
            },{
                test: /\.(sa|sc|c)ss$/,
                use: [
                    {
                        loader: MiniCssExtractPlugin.loader,
                    },
                    'css-loader',
                    'sass-loader',
                ],
            }

        ]
    },
    plugins: [
        // plugins中增加下面内容,实例化热加载插件
        new webpack.HotModuleReplacementPlugin(),
        new HtmlWebPackPlugin({
            template: 'public/index.html',
            filename: 'index.html',
            inject: true
        }),
        new MiniCssExtractPlugin()
    ]
};

在package.json配置scripts如下

1
2
3
4
5
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --mode production",
    "start": "webpack-dev-server --mode development --open"
  },

执行打包

1
npx webpack --mode development

也可以用配置在scripts内的命令打包

1
npm run build

启动服务器

1
npm start

大功告成!!!

当然,这实在太麻烦了,所以其实我用 create-react-app

1
2
3
4
5
6
7
8
# 全局安装
npm install -g create-react-app
# 构建一个my-app的项目
npx create-react-app my-app
cd my-app

# 启动编译当前的React项目,并自动打开 http://localhost:3000/
npm start