webpack构建最基本的React应用

242 阅读1分钟

1. 项目初始化

npm init

或者使用默认值

npm init -y

2. 安装webpack依赖包

npm install webpack webpack-cli --save

安装相应插件

npm install html-webpack-plugin --save

3. 安装react库

npm install react react-dom --save

安装babel-loader解析js文件

npm install babel-loader --save

babel的核心库文件

npm install @babel/core --save

支持jsx文件的插件库

npm install @babel/preset-react --save

4. 配置打包配置文件

在根目录下配置文件webpack.config.js

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {  
    mode: "none", // 根据需要配置  
    entry: './index.js',  
    output: {    
        path: path.join(__dirname, 'dist'),    
        filename: 'js/[name].[hash].js'  
    },  
    module: {    
        rules: [{      
            test: /\.jsx?$/,      
            include: path.resolve(__dirname, './'),      
            use: {        
                loader: 'babel-loader',        
                options: {          
                    presets: [//某些Android Webview不支持async等ES6语法
                       ['@babel/preset-env', {// 该配置必须存在,否则报错regeneratorRuntime is not defined
                            useBuiltIns: 'usage', //不能是“entry”            
                            corejs: 3    
                        }], 
                        '@babel/preset-react'
                    ]        
                }      
             }    
        }]  
    },  
    plugins: [    
        new HtmlWebpackPlugin({      
            template: './index.html'    
        }),  
   ]
};

关于regeneratorRuntime is not defined

5. 配置打包脚本

在package.json中配置打包脚本

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