本文詳細介紹瞭如何從零開始搭建一個 React 開發的腳手架,包含如何添加 Redux 以及 React Router 的環境。javascript
本文代碼地址:react-mobx-starter。css
建議將代碼拉下來以後,配合本文一塊兒查看,效果更佳。html
代碼下載命令:java
git clone -b example https://github.com/beichensky/react-mobx-starter.git
複製代碼
最近將腳手架中的 babel 配置更新到了 7.0.0 版本,因此部分地方做出了修改。目前腳手架中的各種庫的版本以下:node
若是是從低版本升級到 7.0.0
版本,官方提供了一個新的命令能夠直接幫助咱們對項目進行更新:react
npx babel-upgrade --write --install
複製代碼
更多關於 babel-upgrade
的介紹能夠參考官方說明 。webpack
本文的 Demo
分爲兩個環境,一個是開發環境,另外一個是生產環境。nginx
開發環境中講述的是如何配置出一個更好的、更方便的開發環境;git
而生產環境中講述的是如何配置出一個更優化、更小版本的生產環境。github
以前我也就 Webpack
的使用寫了幾篇文章,本文也是在 Webpack
的基礎上進行開發,也是在以前的代碼上進行的擴展。
開發環境的配置是在 從零開始搭建一個 Webpack 開發環境配置(附 Demo) 一文的基礎上進行的擴展。
生產環境的配置是在 使用 Webpack 進行生產環境配置(附 Demo) 一文的基礎上進行的擴展。
建議:對於 Webpack 還不瞭解的朋友,能夠先看一下 從零開始搭建一個 Webpack 開發環境配置(附 Demo) 和 使用 Webpack 進行生產環境配置(附 Demo) 這兩篇文章,能夠更好的入手本文。
雖然本文是在以前文章上進行的擴展,但本文仍是會詳細的介紹每一步的配置。
新建文件夾,命名爲:react-mobx-starter
mkdir react-mobx-starter
複製代碼
初始化 package.json
文件
cd react-mobx-starter
# 直接生成默認的 package.json 文件
npm init -y
複製代碼
建立 src
目錄,用來存放咱們編寫的代碼 建立 public
目錄,用來存放公共的文件 建立 webpack
目錄,用來存放 webpack
配置文件
mkdir src
mkdir public
mkdir webpack
複製代碼
在 src 目錄下 新建 pages 文件夾,用來存放書寫的頁面組件 新建 components 文件夾,用來存放公共組件 新建 utils 文件夾,用來存放經常使用的工具類
cd src
mkdir pages
mkdir components
mkdir utils
複製代碼
在 public
目錄下新建 index.html
文件 在 src
目錄下新建 index.js
文件 在 webpack
目錄下建立 webpack.config.dev.js
和 webpack.config.prod.js
webpack.config.dev.js
用來編寫 webpack 開發環境配置webpack.config.prod.js
用來編寫 webpack 生產環境配置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 + Mobx 全家桶腳手架</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
複製代碼
index.js
function createElement() {
const ele = document.createElement('div');
ele.innerHTML = 'Hello, React';
const root = document.querySelector('#root');
root.appendChild(ele);
}
createElement();
複製代碼
webpack.config.dev.js
和 webpack.config.prod.js
此時尚未書寫內容,咱們以後會詳細的進行講述。
咱們看一下此時的項目結構,以後就能夠進行 webpack 的配置了。
react-mobx-starter
├─ public/
└─ index.html
├─ src/
├─ components/
├─ pages/
├─ utils/
└─ index.js
├─ webpack/
├─ webpack.config.dev.js
└─webpack.config.prod.js
├─ package.json
複製代碼
在 package.json 文件中添加一個執行腳本,用來執行 webpack 命令:
{
...,
"scripts": {
"start": "webpack --config webpack/webpack.config.dev.js"
},
...
}
複製代碼
安裝 webpack 和 webpack-cli
npm install webpack webpack-cli --save-dev
複製代碼
使用 webpack 進行項目配置的時候,必需要有入口和出口,做爲模塊引入和項目輸出。
webpack.config.dev.js
const path = require('path');
const appSrc = path.resolve(__dirname, '../src');
const appDist = path.resolve(__dirname, '../dist');
const appPublic = path.resolve(__dirname, '../public');
const appIndex = path.resolve(appSrc, 'index.js');
module.exports = {
entry: appIndex,
output: {
filename: 'public/js/[name].[hash:8].js',
path: appDist,
publicPath: '/'
}
}
複製代碼
執行 npm run start 腳本,能夠看到 dist/public/js
目錄下多了一個 js
文件,可是這個是由 hash
值命名的的,咱們每次都手動引入到 index.html 文件裏面過於麻煩,因此能夠引入 html-webpack-plugin
插件。
html-webpack-plugin 插件有兩個做用
public
目錄下的文件夾拷貝到 dist
輸出文件夾下dist
下的 js
文件引入到 html
文件中html-webpack-plugin
插件npm install html-webpack-plugin --save-dev
複製代碼
html-webpack-plugin
插件webpack.config.dev.js
const path = require('path');
+ const HTMLWebpackPlugin = require('html-webpack-plugin');
const appSrc = path.resolve(__dirname, '../src');
const appDist = path.resolve(__dirname, '../dist');
const appPublic = path.resolve(__dirname, '../public');
const appIndex = path.resolve(appSrc, 'index.js');
+ const appHtml = path.resolve(appPublic, 'index.html');
module.exports = {
entry: appIndex,
output: {
filename: 'public/js/[name].[hash:8].js',
path: appDist,
publicPath: '/'
},
+ plugins: [
+ new HTMLWebpackPlugin({
+ template: appHtml,
+ filename: 'index.html'
+ })
+ ]
}
複製代碼
webpack 配置中的 mode 屬性,能夠設置爲 'development' 和 'production',咱們目前是進行開發環境配置,因此能夠設置爲 'development'
webpack.config.dev.js
...
module.exports = {
+ mode: 'development',
...
}
複製代碼
爲了方便在項目出錯時,迅速定位到錯誤位置,能夠設置 devtool,生成資源映射,咱們這裏使用 inline-source-map
,更多選擇能夠在這裏查看區別。
webpack.config.dev.js
...
module.exports = {
mode: 'development',
+ devtool: 'inline-source-map',
...
}
複製代碼
npm install webpack-dev-server --save-dev
複製代碼
webpack.config.dev.js
...
module.exports = {
mode: 'development',
devtool: 'inline-source-map',
+ devServer: {
+ contentBase: appPublic,
+ hot: true,
+ host: 'localhost',
+ port: 8000,
+ historyApiFallback: true,
+ // 是否將錯誤展現在瀏覽器蒙層
+ overlay: true,
+ inline: true,
+ // 打印信息
+ stats: 'errors-only',
+ // 設置代理
+ proxy: {
+ '/api': {
+ changeOrigin: true,
+ target: 'https://easy-mock.com/mock/5c2dc9665cfaa5209116fa40/example',
+ pathRewrite: {
+ '^/api/': '/'
+ }
+ }
+ }
+ },
...
}
複製代碼
修改一下 package.json
文件中的 start
腳本:
{
...,
"scripts": {
"start": "webpack-dev-server --config webpack/webpack.config.dev.js"
},
...
}
複製代碼
friendly-errors-webpack-plugin
插件能夠在命令行展現更有好的提示功能。
安裝 friendly-errors-webpack-plugin
:
npm install friendly-errors-webpack-plugin --save-dev
複製代碼
使用 friendly-errors-webpack-plugin
:
webpack.config.dev.js
const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
+ const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
...
module.exports = {
...
plugins: [
new HTMLWebpackPlugin({
template: appHtml,
filename: 'index.html'
}),
+ new FriendlyErrorsWebpackPlugin(),
]
}
複製代碼
webpack.config.dev.js
const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
+ const webpack = require('webpack');
...
module.exports = {
...
plugins: [
...
new FriendlyErrorsWebpackPlugin(),
+ new webpack.HotModuleReplacementPlugin()
]
}
複製代碼
執行 npm run start
命令,命令行提示成功後,在瀏覽器打開 http://localhost:8000
,能夠看到 Hello React
,說明基本的Webpack 配置已經成功了。
咱們如今 index.js
裏面的代碼量比較少,因此沒有問題。可是我若是想在裏面使用一些 ES6 的語法或者是還未被標準定義的 JS 特性,那麼咱們就須要使用 babel 來進行轉換了。下面咱們來配置一下 babel
。
npm install @babel/core babel-loader --save-dev
複製代碼
設置 cacheDirectory 屬性,指定的目錄將用來緩存 loader 的執行結果。以後的 webpack 構建,將會嘗試讀取緩存,來避免在每次執行時,可能產生的、高性能消耗的 Babel 從新編譯過程。
webpack.config.dev.js
...
module.exports = {
...
plugins: [ ... ],
module: {
rules: [
{
test: /\.(js|jsx)$/,
loader: 'babel-loader?cacheDirectory',
include: [ appSrc ],
exclude: /node_modules/
}
]
}
}
複製代碼
babel.config.js
文件是運行時控制文件,在項目編譯的時候會自動讀取 babel.config.js
文件中的 babel
配置。
安裝相關插件:
@babel/preset-env
:能夠在項目中使用全部 ECMAScript
標準裏的最新特性。@babel/preset-react
:能夠在項目中使用 react
語法。npm install babel-preset-env babel-preset-react --save-dev
複製代碼
配置 babel.config.js
文件:
module.exports = (api) => {
api.cache(true);
return {
presets: [
"@babel/preset-env",
"@babel/preset-react"
]
}
}
複製代碼
babel
升級到 7.0.0
版本以後, @babel/preset-stage-0
被廢棄,用到的插件須要本身進行安裝。 若是是從低版本升級到 7.0.0
版本,官方提供了一個新的命令能夠直接幫助咱們對項目進行更新:
npx babel-upgrade --write --install
複製代碼
更多關於 babel-upgrade
的介紹能夠參考官方說明 。
安裝相關插件:
@babel/plugin-proposal-decorators
:能夠在項目中使用裝飾器語法。@babel/plugin-proposal-class-properties
:能夠在項目中使用新的 class 屬性語法。@babel/plugin-transform-runtime
:使用此插件能夠直接使用 babel-runtime 中的代碼對 js
文件進行轉換,避免代碼冗餘。@babel/runtime-corejs2
:配合 babel-plugin-transform-runtime
插件成對使用@babel/plugin-syntax-dynamic-import
:能夠在項目中使用 import()
這種語法@babel/plugin-proposal-export-namespace-from
:可使用 export * 這種命名空間的方式導出模塊@babel/plugin-proposal-throw-expressions
:可使用異常拋出表達式@babel/plugin-proposal-logical-assignment-operators
:可使用邏輯賦值運算符@babel/plugin-proposal-optional-chaining
:可使用可選鏈的方式訪問深層嵌套的屬性或者函數 ?.@babel/plugin-proposal-pipeline-operator
:可使用管道運算符 |>@babel/plugin-proposal-nullish-coalescing-operator
:可使用空值合併語法 ??@babel/plugin-proposal-do-expressions
:可使用 do 表達式(能夠認爲是三元運算符的複雜版本)@babel/plugin-proposal-function-bind
:可使用功能綁定語法 obj::funcnpm install @babel/plugin-proposal-decorators @babel/plugin-proposal-class-properties @babel/plugin-transform-runtime @babel/runtime-corejs2 @babel/plugin-syntax-dynamic-import @babel/plugin-proposal-export-namespace-from @babel/plugin-proposal-throw-expressions @babel/plugin-proposal-logical-assignment-operators @babel/plugin-proposal-optional-chaining @babel/plugin-proposal-pipeline-operator @babel/plugin-proposal-nullish-coalescing-operator @babel/plugin-proposal-do-expressions @babel/plugin-proposal-function-bind --save-dev
複製代碼
配置 babel.config.js
文件:
module.exports = (api) => {
api.cache(true);
return {
presets: [
"@babel/preset-env",
"@babel/preset-react"
],
plugins: [
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
],
[
"@babel/plugin-transform-runtime",
{
"corejs": 2
}
],
[
"@babel/plugin-proposal-class-properties",
{
"loose": true
}
],
"@babel/plugin-syntax-dynamic-import",
// 可使用 export * 這種命名空間的方式導出模塊
"@babel/plugin-proposal-export-namespace-from",
// 可使用異常拋出表達式,
"@babel/plugin-proposal-throw-expressions",
// 默認導出
"@babel/plugin-proposal-export-default-from",
// 可使用邏輯賦值運算符
"@babel/plugin-proposal-logical-assignment-operators",
// 可使用可選鏈的方式訪問深層嵌套的屬性或者函數 ?.
"@babel/plugin-proposal-optional-chaining",
// 可使用管道運算符 |>
[
"@babel/plugin-proposal-pipeline-operator",
{
"proposal": "minimal"
}
],
// 可使用空值合併語法 ??
"@babel/plugin-proposal-nullish-coalescing-operator",
// 可使用 do 表達式(能夠認爲是三元運算符的複雜版本)
"@babel/plugin-proposal-do-expressions",
// 可使用功能綁定語法 obj::func
"@babel/plugin-proposal-function-bind"
]
}
}
複製代碼
這裏須要注意
@babel/plugin-proposal-decorators
插件的放置順序,最好放在第一位,不然可能會出現某些註解失效的問題。
至此,babel 相關的基本配置完成了。以後咱們就能夠在項目中肆意使用各類新的 JS 特性了。
js
文件相關的 babel-loader
配置好了,可是有時候咱們想在項目中爲元素添加一些樣式,而 webpack
中認爲一切都是模塊,因此咱們這時候也須要別的 loader
來解析一波樣式代碼了。
css-loader
:處理 css
文件中的 url()
等。style-loader
:將 css
插入到頁面的 style
標籤。less-loader
:是將 less
文件編譯成 css
。postcss-loader
:能夠集成不少插件,用來操做 css
。咱們這裏使用它集成 autoprefixer
來自動添加前綴。npm install css-loader style-loader less less-loader postcss-loader autoprefixer --save-dev
複製代碼
React
沒法直接使用相似 Vue
中 scope
這種局部做用變量,因此咱們可使用 webpack
提供的 CSS Module
。 二、因爲等會兒會使用 antd
,因此引入 antd
時須要開啓 less
的 javascript
選項,因此要將 less-loader
中的屬性 javascriptEnabled
設置爲 true
。在 webpack.config.dev.js 中配置:
...
const autoprefixer = require('autoprefixer');
module.exports = {
...,
plugins: [...],
module: {
rules: [
...,
{
test: /\.(css|less)$/,
exclude: /node_modules/,
use: [{
loader: 'style-loader'
},
{
loader: 'css-loader',
options: {
sourceMap: true,
modules: true,
localIdentName: '[local].[hash:8]'
}
},
{
loader: 'postcss-loader',
options: {
plugins: () => [autoprefixer()]
}
},
{
loader: 'less-loader',
options: {
javascriptEnabled: true
}
}
]
},
{
test: /\.(css|less)$/,
include: /node_modules/,
use: [{
loader: 'style-loader'
},
{
loader: 'css-loader',
options: {}
},
{
loader: 'postcss-loader',
options: {
plugins: () => [autoprefixer()]
}
},
{
loader: 'less-loader',
options: {
javascriptEnabled: true
}
}
]
},
]
}
}
複製代碼
安裝相關插件:
npm install file-loader csv-loader xml-loader html-loader markdown-loader --save-dev
複製代碼
在 webpack.config.dev.js 中配置:
...
module.exports = {
...,
plugins: [...],
module: {
rules: [
...,
// 解析圖片資源
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
},
// 解析 字體
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
'file-loader'
]
},
// 解析數據資源
{
test: /\.(csv|tsv)$/,
use: [
'csv-loader'
]
},
// 解析數據資源
{
test: /\.xml$/,
use: [
'xml-loader'
]
},
// 解析 MakeDown 文件
{
test: /\.md$/,
use: [
'html-loader',
'markdown-loader'
]
}
]
}
}
複製代碼
在項目開發過程當中,隨着項目愈來愈大, 文件層級愈來愈深,引入文件的時候可能會須要一層一層的找路徑,就會比較繁瑣,咱們可使用 resolve
中的 alias
屬性爲一些經常使用的文件夾設置別名
webpack.config.dev.js
···
module.exports = {
...,
plugins: [...],
module: {...},
+ resolve: {
+ alias: {
+ src: appSrc,
+ utils: path.resolve(__dirname, '../src/utils'),
+ pages: path.resolve(__dirname, '../src/pages'),
+ components: path.resolve(__dirname, '../src/components')
+ }
+ }
}
複製代碼
咱們知道,通常進行模塊搜索時,會從當前目錄下的 node_modules
一直搜索到磁盤根目錄下的 node_modules
。因此爲了減小搜索步驟,咱們能夠設置 resolve.modules
屬性強制只從項目的 node_modules
中查找模塊。
webpack.config.dev.js
···
module.exports = {
...,
plugins: [...],
module: {...},
resolve: {
...,
+ modules: [path.resolve(__dirname, '../node_modules')],
}
}
複製代碼
npm install react react-dom prop-types mobx mobx-react react-router-dom --save
複製代碼
按照 antd
官網的說明,直接在 babel.config.js
文件中添加配置,以後便可在項目中正常使用了。
安裝 antd 相關插件:
npm install antd moment --save
複製代碼
安裝 babel-plugin-import 對組件進行按需加載:
npm install babel-plugin-import --save-dev
複製代碼
在 babel.config.js
文件中添加 antd 配置:
module.exports = (api) => {
api.cache(true);
return {
presets: [
...
],
plugins: [
...,
+ [
+ "import",
+ {
+ "libraryName": "antd",
+ "style": true
+ }
+ ],
...
]
}
複製代碼
基本上須要的插件目前都已經引入了,是時候進行開發了。
index.js
import React from 'react';
import ReactDom from 'react-dom';
import { Provider } from 'mobx-react'
import { LocaleProvider } from 'antd';
import { HashRouter } from 'react-router-dom';
import zh_CN from 'antd/lib/locale-provider/zh_CN';
import 'moment/locale/zh-cn';
import GlobalModel from './GlobalModel';
// import App from './App';
const globalModel = new GlobalModel();
const App = () => {
return <div>開發環境配置完成</div>
}
ReactDom.render(
<Provider globalModel={ globalModel }> <LocaleProvider locale={zh_CN}> <HashRouter> <App /> </HashRouter> </LocaleProvider> </Provider>,
document.querySelector('#root')
);
複製代碼
運行 npm run start
命令,在瀏覽器打開 http://localhost:8000/
,就可以看到 開發環境配置完成 正常顯示。
此時說明咱們各類插件、庫都已經引入完成,能夠正常使用了。
App.js
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import Home from 'pages/home';
import Settings from 'pages/settings';
import Display from 'pages/display';
import NotFound from 'pages/exception'
import styles from './App.less';
export default (props) => {
return (
<div className={ styles.app }>
<Switch>
<Route path='/settings' component={ Settings } />
<Route path='/display' component={ Display } />
<Route exact path='/' component={ Home } />
<Route component={ NotFound } />
</Switch>
</div>
)
}
複製代碼
在 src
目錄下建立 App.less
文件,編寫 App
組件樣式
App.less
.app {
padding: 60px;
}
複製代碼
Home
組件是根路由組件,用來跳轉到 Setting
界面和 Display
界面Settings
組件演示瞭如何獲取和修改 mobx
的全局 Model
Display
組件演示瞭如何使用 mobx 進行同步和異步的數據處理NotFound
組件在匹配不到正確路由時展現Home、Settings、Display 相關的代碼我就不貼了,佔的篇幅較長,你們須要的話能夠去個人 Github 上看一下或者下載下來也能夠。比較方便。地址:Github
index.js
import React from 'react';
import ReactDom from 'react-dom';
import { Provider } from 'mobx-react'
import { LocaleProvider } from 'antd';
import { HashRouter } from 'react-router-dom';
import zh_CN from 'antd/lib/locale-provider/zh_CN';
import 'moment/locale/zh-cn';
import GlobalModel from './GlobalModel';
import App from './App';
const globalModel = new GlobalModel();
ReactDom.render(
<Provider globalModel={ globalModel }> <LocaleProvider locale={zh_CN}> <HashRouter> <App /> </HashRouter> </LocaleProvider> </Provider>,
document.querySelector('#root')
);
複製代碼
能夠看到這裏有一個 GlobalModel
存放全局通用數據的 Model,裏面的邏輯比較簡單,咱們稍微看一下。
GlobalModel.js
import { observable, action } from 'mobx';
export default class GlobalModel {
@observable username = '小明';
@action
changeUserName = (name) => {
this.username = name;
}
}
複製代碼
因爲咱們在 Display 組件中須要進行網絡請求的異步操做,因此咱們這裏引入 fetch 進行網絡請求。
npm install whatwg-fetch qs --save
複製代碼
在 utils
目錄下建立 request.js
文件。
utils/request.js
import 'whatwg-fetch';
import { stringify } from 'qs';
/** * 使用 Get 方式進行網絡請求 * @param {*} url * @param {*} data */
export const get = (url, data) => {
const newUrl = url + '?' + stringify(data) + (stringify(data) === '' ? '' : '&') +'_random=' + Date.now();
return fetch(newUrl, {
cache: 'no-cache',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8'
},
method: 'GET',
})
.then(response => response.json());
}
/** * 進行 Post 方式進行網絡請求 * @param {*} url * @param {*} data */
export const post = (url, data) => {
return fetch(url, {
body: JSON.stringify(data),
cache: 'no-cache',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=utf-8'
},
method: 'POST',
})
.then(response => response.json()) // parses response to JSON
}
複製代碼
執行 npm run start
,編譯成功後,能夠看到界面長這樣。
Home 界面:
Settings 界面:
Display 界面:
NotFound 界面:
{
...,
"scripts": {
"start": "webpack-dev-server --config webpack/webpack.config.dev.js",
"build": "webpack --config webpack/webpack.config.prod.js"
},
...
}
複製代碼
其中大部分的 module
和 plugin
還有 resolve
都與開發環境的一致。因此咱們就以 webpack.config.dev.js
文件中的配置爲基礎進行說明。
安裝相關插件:
npm install uglifyjs-webpack-plugin optimize-css-assets-webpack-plugin --save-dev
複製代碼
添加代碼壓縮配置:
webpack.config.prod.js
...;
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
...;
module.exports = {
mode: 'production',
devtool: 'hidden-source-map',
entry: ...,
output: {...},
plugins: [...],
module: {...},
optimization: {
// 打包壓縮js/css文件
minimizer: [
new UglifyJsPlugin({
uglifyOptions: {
compress: {
// 在UglifyJs刪除沒有用到的代碼時不輸出警告
warnings: false,
// 刪除全部的 `console` 語句,能夠兼容ie瀏覽器
drop_console: true,
// 內嵌定義了可是隻用到一次的變量
collapse_vars: true,
// 提取出出現屢次可是沒有定義成變量去引用的靜態值
reduce_vars: true,
},
output: {
// 最緊湊的輸出
beautify: false,
// 刪除全部的註釋
comments: false,
}
}
}),
new OptimizeCSSAssetsPlugin({})
],
splitChunks: {
cacheGroups: {
styles: {
name: 'styles',
test: /\.(css|less)/,
chunks: 'all',
enforce: true,
reuseExistingChunk: true // 表示是否使用已有的 chunk,若是爲 true 則表示若是當前的 chunk 包含的模塊已經被抽取出去了,那麼將不會從新生成新的。
},
commons: {
name: 'commons',
chunks: 'initial',
minChunks: 2,
reuseExistingChunk: true
},
vendors: {
name: 'vendors',
test: /[\\/]node_modules[\\/]/,
priority: -10,
reuseExistingChunk: true
}
}
},
runtimeChunk: true
},
resolve: {...}
}
複製代碼
安裝相關插件:
npm install mini-css-extract-plugin --save-dev
複製代碼
配置 mini-css-extract-plugin
插件:
plugins
屬性中引入module
的 rules
中使用的 style-loader
替換爲 MiniCssExtractPlugin.loader
webpack.config.prod.js
...
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
...,
plugins: [
...,
new MiniCssExtractPlugin({
filename: 'public/styles/[name].[contenthash:8].css',
chunkFilename: 'public/styles/[name].[contenthash:8].chunk.css'
})
],
modules: {
rules: [
...,
{
test: /\.(css|less)$/,
exclude: /node_modules/,
use: [
{
- loader: 'style-loader'
+ loader: MiniCssExtractPlugin.loader
},
...
]
},
{
test: /\.(css|less)$/,
exclude: /node_modules/,
use: [
{
- loader: 'style-loader'
+ loader: MiniCssExtractPlugin.loader
},
...
]
},
...
]
},
...
}
複製代碼
webpack.config.prod.js
...
module.exports = {
...,
plugins: [
...,
new webpack.DefinePlugin({
// 定義 NODE_ENV 環境變量爲 production
'process.env': {
NODE_ENV: JSON.stringify('production')
}
})
],
...
}
複製代碼
打包的過程當中,因爲部分文件名使用的是 hash 值,會致使每次文件不一樣,於是在 dist 中生成一些多餘的文件。因此咱們能夠在每次打包以前清理一下 dist 目錄。
安裝插件:
npm install clean-webpack-plugin --save-dev
複製代碼
使用插件:
webpack.config.prod.js
...,
module.exports = {
...,
plugins: [
...,
new CleanWebpackPlugin()
],
...
}
複製代碼
webpack.config.prod.js
module.exports = {
...,
stats: {
modules: false,
children: false,
chunks: false,
chunkModules: false
},
performance: {
hints: false
}
}
複製代碼
運行 npm run build
指令,控制檯打包完成以後,根目錄下多出了 dist
文件夾。
我這裏是用的是 Nginx
做爲服務器,發佈在本地。
Nginx
下載地址:nginx.org/en/download…。
下載完成以後,解壓完成。打開 Nginx
目錄,能夠找到一個 conf
文件夾,找到其中的 nginx.conf
文件,修改器中的配置:
將圖中標註的
html
更換爲dist
。
而後咱們就能夠放心的將打包生成的 dist
文件夾直接放到 Nginx
的安裝目錄下了。(此時 dist
目錄與剛纔的 conf
目錄應該是同級的)。
啓動 Nginx
服務:
start nginx
複製代碼
打開瀏覽器,輸入
http://127.0.0.1
或者http://localhost
便可看到咱們的項目已經正常的跑起來了。
Nginx 其餘命令:
# 中止 Nginx 服務
nginx -s stop
# 重啓 Nginx 服務
nginx -s reload
# 退出 nginx
nginx -s quit
複製代碼
更多 Ngnix 相關請參考:Nginx官方文檔
注意:須要在 Nginx 安裝目下執行 nginx 相關命令!
觀察 webpack.config.dev.js
和 webpack.config.prod.js
文件,能夠發現有大量的代碼和配置出現了重複。因此咱們能夠編寫一個 webpack.common.js
文件,將共有的配置放入其中,而後使用 webpack-merge
插件分別引入到 webpack.config.dev.js
和 webpack.config.prod.js
文件中使用。
插件安裝:
npm install webpack-merge --save-dev
複製代碼
使用:
+ const merge = require('webpack-merge');
+ const common = require('./webpack.common.js');
+ module.exports = merge(common, {
+ mode: 'production',
+ ...
+ });
複製代碼
這裏就展現了一下用法,因爲篇幅太長,三個文件中具體的配置代碼我就不貼了, 你們能夠到 個人 GitHub 上查看一下使用 webpack-merge
後的配置文件。
歡迎Star,謝謝各位!
文章及代碼中若有問題,歡迎指正,謝謝!