1.配置插件clean-webpack-plugin, html-webpack-plugin
1) 安装
npm install clean-webpack-plugin html-webpack-plugin -D
2)配置
build/webpack.common.js
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
function webpackCommonConfigCreator(options){
...
return {
...
plugins: [
+ new HtmlWebpackPlugin(),
+ new CleanWebpackPlugin({
+ cleanOnceBeforeBuildPatterns: [path.resolve(process.cwd(), "dist/")]
+ })
]
} }
3)更改入口文件
src/index.js
var ele = document.createElement('div');
ele.innerHTML = "hello webpack";
document.body.appendChild(ele);
执行npm run start
2.配置react
1) 安装react
npm install react react-dom
2)安装babel
npm install @babel/core @babel/cli @babel/preset-env --save -dev
npm install @babel/preset-react --save -dev
npm install babel-loader --save -dev
3)配置babel-loader
build/webpack.common.js
...
function webpackCommonConfigCreator(options){
...
return {
...
+ module: {
+ rules: [
+ {
+ test: /\.(js|jsx)$/,
+ include: path.resolve(__dirname, "../src"),
+ use: [
+ {
+ loader: "babel-loader",
+ options: {
+ presets: ['@babel/preset-react'],
+ }
+ }
+ ]
+ }
+ ]
+ },
...
}
}
4)准备基本的react文件
src/index.js
import React from 'react';
import ReactDom from 'react-dom';
import App from './App.js';
ReactDom.render(<App />, document.getElementById('root'));
src/App.js
import React from 'react';
function App(){
return ( <div> hello react </div> )
}
export default App;
5)创建html模板
创建src/pages/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>react webpack</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
6)添加html插件配置
...
function webpackCommonConfigCreator(options){
...
return {
...
plugins:
[
- new HtmlWebpackPlugin(),
+ new HtmlWebpackPlugin({
+ template: path.resolve(__dirname, "../public/index.html")
+ }),
...
] } }
npm run start 启动本地服务, 编译正常
3.React模块热替换
1)安装loader
npm install react-hot-loader --save-dev
2)配置loader
build/webpack.common.js
...
function webpackCommonConfigCreator(options){
...
return {
...
module: {
rules: [ {
test: /\.(js|jsx)$/,
include: path.resolve(__dirname, "../src"),
use: [ {
loader: "babel-loader",
options: {
presets: ['@babel/preset-react'],
+ plugins: ["react-hot-loader/babel"],
}
} ]
} ]
},
...
}
}
3)修改react代码
src/App.js
+ import {hot} from 'react-hot-loader/root';
...
export default hot(App);
4)开启webpackDevServer热加载
config/webpack.dev.js
...
const config = {
devServer: {
contentBase: path.join(__dirname, "../dist"),
+ hot: true
}
}
...
网友评论