安裝React
命令行輸入并執(zhí)行:cnpm install react react-dom --save
安裝Babel
通過(guò)Babel來(lái)使代碼支持ES語(yǔ)法以及React語(yǔ)法。
命令行輸入并執(zhí)行:npm install --save-dev babel-loader babel-core babel-preset-env babel-preset-react
根目錄下創(chuàng)建.babelrc文件,寫入配置信息
{
"presets": [
"env",
"react"
]
}
修改webpack.base.conf.js文件
// webpack.base.conf.js
const path = require('path');
const APP_PATH = path.resolve(__dirname, '../src');
const DIST_PATH = path.resolve(__dirname, '../dist');
module.exports = {
entry: {
app: './src/index.js'
},
output: {
filename: 'js/bundle.js',
path: DIST_PATH
},
module: {
rules: [
{
test: /\.js?$/, //對(duì)于js使用babel編譯成es5
use: "babel-loader",
include: APP_PATH
}
]
}
};
在src/index.js文件使用react
import React from "react";
import ReactDom from "react-dom";
ReactDom.render(
<h1>hello, world!</h1>,
document.getElementById("root")
);
這時(shí)候運(yùn)行npm run build即可打包
然后在我的打包過(guò)程中出現(xiàn)如下圖錯(cuò)誤提示:

image.png
根據(jù)提示重新安裝了babel-loader@7,最終打包成功。
安裝HtmlWebpackPlugin
打包好的js需要我們手動(dòng)在html引入才可使用,通過(guò)webpack中的HtmlWebpackPlugin即可實(shí)現(xiàn)自動(dòng)引入。
命令行輸入并執(zhí)行:npm install --save-dev html-webpack-plugin
在webpack.prod.conf.js引入
// webpack.prod.conf.js
const merge = require('webpack-merge'); //合并
const baseWebpackConfig = require('./webpack.base.conf');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = merge(baseWebpackConfig, {
mode: 'production', //webpack4新增mode,"production" | "development" | "none"
plugins: [
new HtmlWebpackPlugin({
template: 'index.html',
minify: {
removeComments: true, // 移除HTML中的注釋
collapseWhitespace: true, // 刪除空白符與換行符
},
}),
]
});