This time I will show you how to use webpack to build a react development environment, and what are the precautions for using webpack to build a react development environment. The following is a practical case, let's take a look.
mkdir react-redux && cd react-redux npm init -y
2. Install webpack
npm i webpack -D
npm install -D webpack webpack-cli
3. Create a new project structure
react-redux |- package.json + |- /dist + |- index.html |- /src |- index.js
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p id="root"></p> <script src="bundle.js"></script> </body> </html>
document.querySelector('#root').innerHTML = 'webpack使用';
node_modules\.bin\webpack src\index.js --output dist\bundle.js --mode development
to configure webpack
1. Use theconst path=require('path'); module.exports={ entry:'./src/index.js', output:{ filename:'bundle.js', path:path.resolve(dirname,'dist') } };
node_modules\.bin\webpack --mode production You can package 2.NPM Scripts (NPM Scripts) Add an npm script in package.json (npm script):
"build": "webpack --mode production" Run
npm run build to package
Build using webpack Local server
webpack-dev-server provides a simple web server and can be reloaded in real time. 1. Installation npm i -D webpack-dev-server Modify the configuration file webpack.config.js
const path=require('path'); module.exports={ entry:'./src/index.js', output:{ filename:'bundle.js', path:path.resolve(dirname,'dist') }, //以下是新增的配置 devServer:{ contentBase: "./dist",//本地服务器所加载的页面所在的目录 historyApiFallback: true,//不跳转 inline: true,//实时刷新 port:3000, open:true,//自动打开浏览器 } };
"start": "webpack-dev-server --open --mode development"
plugins:[ //热更新,不是刷新 new webpack.HotModuleReplacementPlugin() ],
if (module.hot){ //实现热更新 module.hot.accept(); }
devServer:{ contentBase: "./dist",//本地服务器所加载的页面所在的目录 historyApiFallback: true,//不跳转 inline: true,//实时刷新 port:3000, open:true,//自动打开浏览器 hot:true //开启热更新 },
Configure Html template
1. Install the html-webpack-plugin pluginnpm i html-webpack-plugin -D
const path=require('path'); let webpack=require('webpack'); let HtmlWebpackPlugin=require('html-webpack-plugin'); module.exports={ entry:'./src/index.js', output:{ //添加hash可以防止文件缓存,每次都会生成4位hash串 filename:'bundle.[hash:4].js', path:path.resolve('dist') }, //以下是新增的配置 devServer:{ contentBase: "./dist",//本地服务器所加载的页面所在的目录 historyApiFallback: true,//不跳转 inline: true,//实时刷新 port:3000, open:true,//自动打开浏览器 hot:true //开启热更新 }, plugins:[ new HtmlWebpackPlugin({ template:'./src/index.html', hash:true, //会在打包好的bundle.js后面加上hash串 }) ] };
npm run build for packaging. At this time, it will be in the dist directory every time npm run build Create a lot of packaged packages. You should clear the files in the dist directory before each package, and then put the packaged files into it. The clean-webpack-plugin plug-in is used here. Pass
npm i clean-webpack-plugin -D command to install. Then reference the plug-in in webpack.config.js.
const path=require('path'); let webpack=require('webpack'); let HtmlWebpackPlugin=require('html-webpack-plugin'); let CleanWebpackPlugin=require('clean-webpack-plugin'); module.exports={ entry:'./src/index.js', output:{ //添加hash可以防止文件缓存,每次都会生成4位hash串 filename:'bundle.[hash:4].js', path:path.resolve('dist') }, //以下是新增的配置 devServer:{ contentBase: "./dist",//本地服务器所加载的页面所在的目录 historyApiFallback: true,//不跳转 inline: true,//实时刷新 port:3000, open:true,//自动打开浏览器 hot:true //开启热更新 }, plugins:[ new HtmlWebpackPlugin({ template:'./src/index.html', hash:true, //会在打包好的bundle.js后面加上hash串 }), //打包前先清空 new CleanWebpackPlugin('dist') ] };
Compile es6 and jsx
1. Install babelnpm i babel-core babel-loader babel-preset-env babel-preset-react babel-preset-stage-0 -D babel-loader : babelLoader babel-preset-env: Only compiles features that are not yet supported according to the configured env. babel-preset-react: Convert jsx to js
{ "presets": ["env", "stage-0","react"] //从左向右解析 }
const path=require('path'); module.exports={ entry:'./src/index.js', output:{ filename:'bundle.js', path:path.resolve(dirname,'dist') }, //以下是新增的配置 devServer:{ contentBase: "./dist",//本地服务器所加载的页面所在的目录 historyApiFallback: true,//不跳转 inline: true//实时刷新 }, module:{ rules:[ { test:/\.js$/, exclude:/(node_modules)/, //排除掉nod_modules,优化打包速度 use:{ loader:'babel-loader' } } ] } };
Separation of development environment and production environment
1. Install webpack-mergenpm install --save-dev webpack-merge
const path=require('path'); let webpack=require('webpack'); let HtmlWebpackPlugin=require('html-webpack-plugin'); let CleanWebpackPlugin=require('clean-webpack-plugin'); module.exports={ entry:['babel-polyfill','./src/index.js'], output:{ //添加hash可以防止文件缓存,每次都会生成4位hash串 filename:'bundle.[hash:4].js', path:path.resolve(dirname,'dist') }, plugins:[ new HtmlWebpackPlugin({ template:'./src/index.html', hash:true, //会在打包好的bundle.js后面加上hash串 }), //打包前先清空 new CleanWebpackPlugin('dist'), new webpack.HotModuleReplacementPlugin() //查看要修补(patch)的依赖 ], module:{ rules:[ { test:/\.js$/, exclude:/(node_modules)/, //排除掉nod_modules,优化打包速度 use:{ loader:'babel-loader' } } ] } };
const merge=require('webpack-merge'); const path=require('path'); let webpack=require('webpack'); const common=require('./webpack.common.js'); module.exports=merge(common,{ devtool:'inline-soure-map', mode:'development', devServer:{ historyApiFallback: true, //在开发单页应用时非常有用,它依赖于HTML5 history API,如果设置为true,所有的跳转将指向index.html contentBase:path.resolve(dirname, '../dist'),//本地服务器所加载的页面所在的目录 inline: true,//实时刷新 open:true, compress: true, port:3000, hot:true //开启热更新 }, plugins:[ //热更新,不是刷新 new webpack.HotModuleReplacementPlugin(), ], });
const merge = require('webpack-merge'); const path=require('path'); let webpack=require('webpack'); const UglifyJSPlugin = require('uglifyjs-webpack-plugin'); const common = require('./webpack.common.js'); module.exports = merge(common, { mode:'production', plugins: [ new UglifyJSPlugin() ] });
Configure react
1. Install react,react-dom npm i react react-dom -S
import React from 'react'; class App extends React.Component{ render(){ return (<p>佳佳加油</p>); } } export default App;
import React from 'react'; import ReactDOM from 'react-dom'; import {AppContainer} from 'react-hot-loader'; import App from './App'; ReactDOM.render( <AppContainer> <App/> </AppContainer>, document.getElementById('root') ); if (module.hot) { module.hot.accept(); }
4.安装 react-hot-loader
npm i -D react-hot-loader
5.修改配置文件 在 webpack.config.js 的 entry 值里加上 react-hot-loader/patch,一定要写在entry 的最前面,如果有 babel-polyfill 就写在babel-polyfill 的后面
6.在 .babelrc 里添加 plugin, "plugins": ["react-hot-loader/babel"]
处理SASS
1.安装 style-loader css-loader url-loader
npm install style-loader css-loader url-loader --save-dev
2.安装 sass-loader node-sass
npm install sass-loader node-sass --save-dev
3.安装 mini-css-extract-plugin ,提取单独打包css文件
npm install --save-dev mini-css-extract-plugin
4.配置webpack配置文件
webpack.common.js
{ test:/\.(png|jpg|gif)$/, use:[ "url-loader" ] },
webpack.dev.js
{ test:/\.scss$/, use:[ "style-loader", "css-loader", "sass-loader" ] }
webpack.prod.js
const merge = require('webpack-merge'); const path=require('path'); let webpack=require('webpack'); const MiniCssExtractPlugin=require("mini-css-extract-plugin"); const UglifyJSPlugin = require('uglifyjs-webpack-plugin'); const common = require('./webpack.common.js'); module.exports = merge(common, { mode:'production', module:{ rules:[ { test:/\.scss$/, use:[ // fallback to style-loader in development process.env.NODE_ENV !== 'production' ? 'style-loader' : MiniCssExtractPlugin.loader, "css-loader", "sass-loader" ] } ] }, plugins: [ new UglifyJSPlugin(), new MiniCssExtractPlugin({ // Options similar to the same options in webpackOptions.output // both options are optional filename: "[name].css", chunkFilename: "[id].css" }) ] });
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of How to use webpack to build a react development environment. For more information, please follow other related articles on the PHP Chinese website!