33从0开始使用webpack构建一个React脚手架
44
55## 项目使用:
6- ```
6+ ``` js
77git clone git@github .com : TigerHee/ react- cli- diy .git
88
99cd react- cli- diy
@@ -35,7 +35,7 @@ npm run build
3535` npm i webpack webpack-cli webpack-merge -D `
3636
3737修改webpack.config.js文件:
38- ```
38+ ``` js
3939module .exports = {
4040 entry: ' ./src/index.js' , // 入口
4141 output: { // 出口
@@ -46,7 +46,7 @@ module.exports = {
4646```
4747使用webpack-merge包merge公共配置文件分别到生产和开发配置文件:
4848
49- ```
49+ ``` js
5050const merge = require (' webpack-merge' )
5151const baseConfig = require (' ./webpack.config.js' )
5252
@@ -61,7 +61,7 @@ module.exports = merge(baseConfig, {
6161
6262公共配置内使用` html-webpack-plugin ` 来使用index.html模版:
6363
64- ```
64+ ``` js
6565plugins: [
6666 new HtmlWebpackPlugin ({
6767 template: ' ./public/index.html' ,
@@ -76,7 +76,7 @@ plugins: [
7676```
7777开发模式需要使用到开发服务器:
7878
79- ```
79+ ``` js
8080devServer: { // 内置开发服务器配置
8181 port: 3000 ,
8282 progress: true ,
@@ -90,7 +90,7 @@ devServer: { // 内置开发服务器配置
9090
9191配置好上诉基本配置之后在` package.json ` 内设置启动脚本:
9292
93- ```
93+ ``` js
9494" scripts" : {
9595 " build" : " webpack --config webpack.prod.js" ,
9696 " dev" : " webpack-dev-server --config webpack.dev.js"
@@ -99,7 +99,7 @@ devServer: { // 内置开发服务器配置
9999
100100接下来在公共配置里设置处理css与less:
101101
102- ```
102+ ``` js
103103rules: [
104104 {
105105 test: / \. (css| less)$ / ,
@@ -118,7 +118,7 @@ postcss-loader处理兼容前缀需要一个单独的配置文件postcss.config.
118118
119119` npm i mini-css-extract-plugin -D `
120120
121- ```
121+ ``` js
122122const MiniCssExtractPlugin = require (' mini-css-extract-plugin' );
123123
124124{
@@ -151,7 +151,7 @@ const MiniCssExtractPlugin = require('mini-css-extract-plugin');
151151
152152修改生产环境配置:
153153
154- ```
154+ ``` js
155155const { CleanWebpackPlugin } = require (' clean-webpack-plugin' );
156156
157157plugins: [
@@ -165,7 +165,7 @@ plugins:[
165165
166166` npm i optimize-css-assets-webpack-plugin uglifyjs-webpack-plugin -D `
167167
168- ```
168+ ``` js
169169optimization: { // 优化项
170170 minimizer: [
171171 new UglifyJsPlugin ({ // 优化js
@@ -185,7 +185,7 @@ optimization: { // 优化项
185185
186186` npm i @babel/preset-react -D `
187187
188- ```
188+ ``` js
189189{
190190 test: / \. (js| jsx)$ / ,
191191 use: {
@@ -215,7 +215,7 @@ optimization: { // 优化项
215215
216216` npm i file-loader url-loader -D `
217217
218- ```
218+ ``` js
219219{
220220 test: / \. (png| jpg| gif)$ / ,
221221 use: {
@@ -230,7 +230,7 @@ optimization: { // 优化项
230230
231231开发模式需要监听更改热更新:
232232
233- ```
233+ ``` js
234234watch: true ,
235235watchOptions: {
236236 poll: 1000 , // 每秒监听1000次
@@ -243,7 +243,7 @@ watchOptions: {
243243
244244定义可能会用到的全局环境变量:
245245
246- ```
246+ ``` js
247247const webpack = require (' webpack' );
248248
249249// 生产环境:
@@ -263,7 +263,7 @@ plugins: [
263263
264264再在压缩代码里加个版权声明:
265265
266- ```
266+ ``` js
267267const webpack = require (' webpack' );
268268
269269plugins: [
0 commit comments