相關連接html
clean-webpack-plugin
、 html-webpack-plugin
, 這兩個插件基本上是必配的了** 官網指南關於這個插件部份內容已通過時沒有更新,按照官網配置會出錯,因此參考github上這個插件文檔來配置, 文檔地址: github.com/johnagan/cl…react
yarn add clean-webpack-plugin html-webpack-plugin -D
複製代碼
config/webpack.common.jswebpack
...
+ 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(), "build/"), path.resolve(process.cwd(), "dist/")]
+ }),
]
}
}
...
複製代碼
src/index.jsgit
var ele = document.createElement('div');
ele.innerHTML = "hello webpack";
document.body.appendChild(ele);
複製代碼
yarn start
, 效果:github
yarn build
, build目錄下生成index.html而且引入了bundle.jsweb
接下來配置react瀏覽器
yarn add react react-dom
複製代碼
yarn add @babel/core @babel/cli @babel/preset-env -D
yarn add @babel/preset-react -D
yarn add babel-loader -D
複製代碼
config/webpack.common.jsbash
...
function webpackCommonConfigCreator(options){
...
return {
...
+ module: {
+ rules: [
+ {
+ test: /\.(js|jsx)$/,
+ include: path.resolve(__dirname, "../src"),
+ use: [
+ {
+ loader: "babel-loader",
+ options: {
+ presets: ['@babel/preset-react'],
+ }
+ }
+ ]
+ }
+ ]
+ },
...
}
}
複製代碼
src/index.jsbabel
import React from 'react';
import ReactDom from 'react-dom';
import App from './App.js';
ReactDom.render(<App />, document.getElementById('root'));
複製代碼
src/App.jsapp
import React from 'react';
function App(){
return (
<div>
hello react
</div>
)
}
export default App;
複製代碼
root
的div上,而html-webpack-plugin
插件默認生成的html沒有這個div, 因此須要配置插件使用咱們定義的模板建立public/index.html
public/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>
複製代碼
config/webpack.common.js
...
function webpackCommonConfigCreator(options){
...
return {
...
plugins: [
- new HtmlWebpackPlugin(),
+ new HtmlWebpackPlugin({
+ template: path.resolve(__dirname, "../public/index.html")
+ }),
...
]
}
}
複製代碼
yarn start
, 編譯正常開發模式下,改動代碼,瀏覽器將刷新頁面來更新改動,配置模塊熱替換,瀏覽器不刷新,而是經過dom操做來更新改動,對頻繁更新代碼的開發模式更加友好
yarn add react-hot-loader -D
複製代碼
config/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"],
}
}
]
}
]
},
...
}
}
複製代碼
src/App.js
+ import {hot} from 'react-hot-loader/root';
...
export default hot(App);
複製代碼
config/webpack.dev.js
...
const config = {
devServer: {
contentBase: path.join(__dirname, "../dist"),
+ hot: true
}
}
...
複製代碼
相關連接
源碼github倉庫: github.com/tanf1995/We…