分析vue-cli@2.9.3 搭建的webpack專案工程

若川發表於2018-06-11

前言

已經有很多分析Vue-cli搭建工程的文章,為什麼自己還要寫一遍呢。學習就好比是座大山,人們沿著不同的路登山,分享著自己看到的風景。你不一定能看到別人看到的風景,體會到別人的心情。只有自己去登山,才能看到不一樣的風景,體會才更加深刻。

專案放在筆者的github上,分析vue-cli@2.9.3 搭建的webpack專案工程。方便大家克隆下載,或者線上檢視。同時也求個star ^_^,也是對筆者的一種鼓勵和支援。

正文從這裡開始~

使用vue-cli初始化webpack工程

// # 安裝npm install -g vue-cli// 安裝完後vue命令就可以使用了。實際上是全域性註冊了vue、vue-init、vue-list幾個命令// # ubuntu 系統下// [vue-cli@2.9.3] link /usr/local/bin/vue@ ->
/usr/local/lib/node_modules/vue-cli/bin/vue// [vue-cli@2.9.3] link /usr/local/bin/vue-init@ ->
/usr/local/lib/node_modules/vue-cli/bin/vue-init// [vue-cli@2.9.3] link /usr/local/bin/vue-list@ ->
/usr/local/lib/node_modules/vue-cli/bin/vue-listvue list// 可以發現有browserify、browserify-simple、pwa、simple、webpack、webpack-simple幾種模板可選,這裡選用webpack。// # 使用 vue initvue init <
template-name>
<
project-name>
// # 例子vue init webpack analyse-vue-cli複製程式碼

更多vue-cli如何工作的可以檢視這篇文章vue-cli是如何工作的,或者分析Vue-cli原始碼檢視這篇走進Vue-cli原始碼,自己動手搭建前端腳手架工具,再或者直接檢視vue-cli github倉庫原始碼

如果對webpack還不是很瞭解,可以檢視webpack官方文件中的概念,雖然是最新版本的,但概念都是差不多的。

package.json

分析一個專案,一般從package.json的命令入口scripts開始。

"scripts": { 
// dev webpack-dev-server --inline 模式 --progress 顯示進度 --config 指定配置檔案(預設是webpack.config.js) "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js", "start": "npm run dev", // jest測試 "unit": "jest --config test/unit/jest.conf.js --coverage", // e2e測試 "e2e": "node test/e2e/runner.js", // 執行jest測試和e2e測試 "test": "npm run unit &
&
npm run e2e"
, // eslint --ext 指定副檔名和相應的檔案 "lint": "eslint --ext .js,.vue src test/unit test/e2e/specs", // node 執行build/build.js檔案 "build": "node build/build.js"
},複製程式碼

Npm Script 底層實現原理是通過呼叫 Shell 去執行指令碼命令。npm run start等同於執行npm run dev

Npm Script 還有一個重要的功能是能執行安裝到專案目錄裡的 node_modules 裡的可執行模組。

例如在通過命令npm i -D webpack-dev-serverwebpack-dev-server安裝到專案後,是無法直接在專案根目錄下通過命令 webpack-dev-server 去執行 webpack-dev-server 構建的,而是要通過命令 ./node_modules/.bin/webpack-dev-server 去執行。

Npm Script 能方便的解決這個問題,只需要在 scripts 欄位裡定義一個任務,例如:

"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js"複製程式碼

Npm Script 會先去專案目錄下的 node_modules 中尋找有沒有可執行的 webpack-dev-server 檔案,如果有就使用本地的,如果沒有就使用全域性的。 所以現在執行 webpack-dev-server 啟動服務時只需要通過執行 npm run dev 去實現。

再來看下 npm run devwebpack-dev-server 其實是一個node.js的應用程式,它是通過JavaScript開發的。在命令列執行npm run dev命令等同於執行node ./node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --progress --config build/webpack.dev.conf.js。你可以試試。

更多package.json的配置項,可以檢視阮一峰老師的文章 package.json檔案

npm run dev指定了build/webpack.dev.conf.js配置去啟動服務,那麼我們來看下這個檔案做了什麼。

build/webpack.dev.conf.js webpack開發環境配置

這個檔案主要做了以下幾件事情:
1、引入各種依賴,同時也引入了config資料夾下的變數和配置,和一個工具函式build/utils.js
2、合併build/webpack.base.conf.js配置檔案,
3、配置開發環境一些devServerplugin等配置,
4、最後匯出了一個Promise,根據配置的埠,尋找可用的埠來啟動服務。

具體可以看build/webpack.dev.conf.js這個檔案註釋:

'use strict'// 引入工具函式const utils = require('./utils')// 引入webpackconst webpack = require('webpack')// 引入config/index.js配置const config = require('../config')// 合併webpack配置const merge = require('webpack-merge')const path = require('path')// 基本配置const baseWebpackConfig = require('./webpack.base.conf')// 拷貝外掛const CopyWebpackPlugin = require('copy-webpack-plugin')// 生成html的外掛const HtmlWebpackPlugin = require('html-webpack-plugin')// 友好提示的外掛 https://github.com/geowarin/friendly-errors-webpack-pluginconst FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')// 查詢可用埠 // github倉庫 https://github.com/indexzero/node-portfinderconst portfinder = require('portfinder')// process模組用來與當前程式互動,可以通過全域性變數process訪問,不必使用require命令載入。它是一個EventEmitter物件的例項。// 後面有些process模組用到的,所以這裡統一列舉下。// 更多檢視這篇阮一峰的這篇文章 http://javascript.ruanyifeng.com/nodejs/process.html// process物件提供一系列屬性,用於返回系統資訊。// process.pid:當前程式的程式號。// process.version:Node的版本,比如v0.10.18。// process.platform:當前系統平臺,比如Linux。// process.title:預設值為“node”,可以自定義該值。// process.argv:當前程式的命令列引數陣列。// process.env:指向當前shell的環境變數,比如process.env.HOME。// process.execPath:執行當前程式的可執行檔案的絕對路徑。// process.stdout:指向標準輸出。// process.stdin:指向標準輸入。// process.stderr:指向標準錯誤。// process物件提供以下方法:// process.exit():退出當前程式。// process.cwd():返回執行當前指令碼的工作目錄的路徑。_// process.chdir():改變工作目錄。// process.nextTick():將一個回撥函式放在下次事件迴圈的頂部。// hostconst HOST = process.env.HOST// 埠const PORT = process.env.PORT &
&
Number(process.env.PORT)// 合併基本的webpack配置const devWebpackConfig = merge(baseWebpackConfig, {
module: {
// cssSourceMap這裡配置的是true rules: utils.styleLoaders({
sourceMap: config.dev.cssSourceMap, usePostCSS: true
})
}, // cheap-module-eval-source-map is faster for development // 在開發環境是cheap-module-eval-source-map選項更快 // 這裡配置的是cheap-module-eval-source-map // 更多可以檢視中文文件:https://webpack.docschina.org/configuration/devtool/#devtool // 英文 https://webpack.js.org/configuration/devtool/#development devtool: config.dev.devtool, // these devServer options should be customized in /config/index.js devServer: {
// 配置在客戶端的日誌等級,這會影響到你在瀏覽器開發者工具控制檯裡看到的日誌內容。 // clientLogLevel 是列舉型別,可取如下之一的值 none | error | warning | info。 // 預設為 info 級別,即輸出所有型別的日誌,設定成 none 可以不輸出任何日誌。 clientLogLevel: 'warning', // historyApiFallback boolean object 用於方便的開發使用了 HTML5 History API 的單頁應用。 // 可以簡單true 或者 任意的 404 響應可以提供為 index.html 頁面。 historyApiFallback: {
rewrites: [ // config.dev.assetsPublicPath 這裡是 / {
from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html')
}, ],
}, // 開啟熱更新 hot: true, // contentBase 配置 DevServer HTTP 伺服器的檔案根目錄。 // 預設情況下為當前執行目錄,通常是專案根目錄,所有一般情況下你不必設定它,除非你有額外的檔案需要被 DevServer 服務。 contentBase: false, // since we use CopyWebpackPlugin. // compress 配置是否啟用 gzip 壓縮。boolean 為型別,預設為 false。 compress: true, // host // 例如你想要區域網中的其它裝置訪問你本地的服務,可以在啟動 DevServer 時帶上 --host 0.0.0.0 // 或者直接設定為 0.0.0.0 // 這裡配置的是localhost host: HOST || config.dev.host, // 埠號 這裡配置的是8080 port: PORT || config.dev.port, // 開啟瀏覽器,這裡配置是不開啟false open: config.dev.autoOpenBrowser, // 是否在瀏覽器以遮罩形式顯示報錯資訊 這裡配置的是true overlay: config.dev.errorOverlay ? {
warnings: false, errors: true
} : false, // 這裡配置的是 / publicPath: config.dev.assetsPublicPath, // 代理 這裡配置的是空{
},有需要可以自行配置 proxy: config.dev.proxyTable, // 啟用 quiet 後,除了初始啟動資訊之外的任何內容都不會被列印到控制檯。這也意味著來自 webpack 的錯誤或警告在控制檯不可見。 // 開啟後一般非常乾淨只有類似的提示 Your application is running here: http://localhost:8080 quiet: true, // necessary for FriendlyErrorsPlugin // webpack-dev-middleware // watch: false, // 啟用 Watch 模式。這意味著在初始構建之後,webpack 將繼續監聽任何已解析檔案的更改。Watch 模式預設關閉。 // webpack-dev-server 和 webpack-dev-middleware 裡 Watch 模式預設開啟。 // Watch 模式的選項 watchOptions: {
// 或者指定毫秒為單位進行輪詢。 // 這裡配置為false poll: config.dev.poll,
} // 更多檢視中文文件:https://webpack.docschina.org/configuration/watch/#src/components/Sidebar/Sidebar.jsx
}, plugins: [ // 定義為開發環境 new webpack.DefinePlugin({
// 這裡是 {
NODE_ENV: '"development"'
} 'process.env': require('../config/dev.env')
}), // 熱更新外掛 new webpack.HotModuleReplacementPlugin(), // 熱更新時顯示具體的模組路徑 new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update. // 在編譯出現錯誤時,使用 NoEmitOnErrorsPlugin 來跳過輸出階段。 new webpack.NoEmitOnErrorsPlugin(), // github倉庫 https://github.com/ampedandwired/html-webpack-plugin new HtmlWebpackPlugin({
filename: 'index.html', template: 'index.html', // inject 預設值 true,script標籤位於html檔案的 body 底部 // body 通true, header, script 標籤位於 head 標籤內 // false 不插入生成的 js 檔案,只是單純的生成一個 html 檔案 inject: true
}), // copy custom static assets // 把static資源複製到相應目錄。 new CopyWebpackPlugin([ {
// 這裡是 static from: path.resolve(__dirname, '../static'), // 這裡是 static to: config.dev.assetsSubDirectory, // 忽略.開頭的檔案。比如這裡的.gitkeep,這個檔案是指空資料夾也提交到git ignore: ['.*']
} ]) ]
})// 匯出一個promisemodule.exports = new Promise((resolve, reject) =>
{
// process.env.PORT 可以在命令列指定埠號,比如PORT=2000 npm run dev,那訪問就是http://localhost:2000 // config.dev.port 這裡配置是 8080 portfinder.basePort = process.env.PORT || config.dev.port // 以配置的埠為基準,尋找可用的埠,比如:如果8080佔用,那就8081,以此類推 // github倉庫 https://github.com/indexzero/node-portfinder portfinder.getPort((err, port) =>
{
if (err) {
reject(err)
} else {
// publish the new Port, necessary for e2e tests process.env.PORT = port // add port to devServer config devWebpackConfig.devServer.port = port // Add FriendlyErrorsPlugin devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
compilationSuccessInfo: {
messages: [`Your application is running here: http://${devWebpackConfig.devServer.host
}
:${port
}
`],
}, // notifyOnErrors 這裡配置是 true // onErrors 是一個函式,出錯輸出錯誤資訊,系統原生的通知 onErrors: config.dev.notifyOnErrors ? utils.createNotifierCallback() : undefined
})) resolve(devWebpackConfig)
}
})
})複製程式碼

build/utils.js 工具函式

上文build/webpack.dev.conf.js提到引入了build/utils.js工具函式。
該檔案主要寫了以下幾個工具函式:
1、assetsPath返回輸出路徑,
2、cssLoaders返回相應的css-loader配置,
3、styleLoaders返回相應的處理樣式的配置,
4、createNotifierCallback建立啟動服務時出錯時提示資訊回撥。

具體配置可以看該檔案註釋:

'use strict'const path = require('path')// 引入配置檔案config/index.jsconst config = require('../config')// 提取css的外掛const ExtractTextPlugin = require('extract-text-webpack-plugin')// 引入package.json配置const packageConfig = require('../package.json')// 返回路徑exports.assetsPath = function (_path) { 
const assetsSubDirectory = process.env.NODE_ENV === 'production' // 二級目錄 這裡是 static ? config.build.assetsSubDirectory // 二級目錄 這裡是 static : config.dev.assetsSubDirectory // 生成跨平臺相容的路徑 // 更多檢視Node API連結:https://nodejs.org/api/path.html#path_path_posix return path.posix.join(assetsSubDirectory, _path)
}exports.cssLoaders = function (options) {
// 作為引數傳遞進來的options物件 // {
// // sourceMap這裡是true // sourceMap: true, // // 是否提取css到單獨的css檔案 // extract: true, // // 是否使用postcss // usePostCSS: true //
} options = options || {
} const cssLoader = {
loader: 'css-loader', options: {
sourceMap: options.sourceMap
}
} const postcssLoader = {
loader: 'postcss-loader', options: {
sourceMap: options.sourceMap
}
} // generate loader string to be used with extract text plugin // 建立對應的loader配置 function generateLoaders (loader, loaderOptions) {
// 是否使用usePostCSS,來決定是否採用postcssLoader const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader] if (loader) {
loaders.push({
loader: loader + '-loader', // 合併 loaderOptions 生成options options: Object.assign({
}, loaderOptions, {
sourceMap: options.sourceMap
})
})
} // Extract CSS when that option is specified // (which is the case during production build) if (options.extract) {
// 如果提取使用ExtractTextPlugin外掛提取 // 更多配置 看外掛中文文件:https://webpack.docschina.org/plugins/extract-text-webpack-plugin/ return ExtractTextPlugin.extract({
// 指需要什麼樣的loader去編譯檔案 // loader 被用於將資源轉換成一個 CSS 匯出模組 (必填) use: loaders, // loader(例如 'style-loader')應用於當 CSS 沒有被提取(也就是一個額外的 chunk,當 allChunks: false) fallback: 'vue-style-loader'
})
} else {
return ['vue-style-loader'].concat(loaders)
}
} // https://vue-loader.vuejs.org/en/configurations/extract-css.html return {
css: generateLoaders(), postcss: generateLoaders(), less: generateLoaders('less'), // sass indentedSyntax 語法縮排,類似下方格式 // #main // color: blue // font-size: 0.3em sass: generateLoaders('sass', {
indentedSyntax: true
}), scss: generateLoaders('sass'), stylus: generateLoaders('stylus'), styl: generateLoaders('stylus')
}
}// Generate loaders for standalone style files (outside of .vue)// 最終會返回webpack css相關的配置exports.styleLoaders = function (options) {
// {
// // sourceMap這裡是true // sourceMap: true, // // 是否提取css到單獨的css檔案 // extract: true, // // 是否使用postcss // usePostCSS: true //
} const output = [] const loaders = exports.cssLoaders(options) for (const extension in loaders) {
const loader = loaders[extension] output.push({
test: new RegExp('\\.' + extension + '$'), use: loader
})
} return output
}// npm run dev 出錯時, FriendlyErrorsPlugin外掛 配置 onErrors輸出錯誤資訊exports.createNotifierCallback = () =>
{
// 'node-notifier'是一個跨平臺系統通知的頁面,當遇到錯誤時,它能用系統原生的推送方式給你推送資訊 const notifier = require('node-notifier') return (severity, errors) =>
{
if (severity !== 'error') return const error = errors[0] const filename = error.file &
&
error.file.split('!').pop() notifier.notify({
title: packageConfig.name, message: severity + ': ' + error.name, subtitle: filename || '', icon: path.join(__dirname, 'logo.png')
})
}
}複製程式碼

build/webpack.base.conf.js webpack基本配置檔案

上文build/webpack.dev.conf.js提到引入了build/webpack.base.conf.js這個webpack基本配置檔案。
這個檔案主要做了以下幾件事情:
1、引入各種外掛、配置等,其中引入了build/vue-loader.conf.js相關配置,
2、建立eslint規則配置,預設啟用,
3、匯出webpack配置物件,其中包含context,入口entry,輸出outputresolvemodule下的rules(處理對應檔案的規則),和node相關的配置等。

具體可以看這個檔案註釋:

// 使用嚴格模式,更多嚴格模式可以檢視// [阮一峰老師的es標準入門](http://es6.ruanyifeng.com/?search=%E4%B8%A5%E6%A0%BC%E6%A8%A1%E5%BC%8F&
x=0&
y=0#docs/function#%E4%B8%A5%E6%A0%BC%E6%A8%A1%E5%BC%8F)'use strict'const path = require('path')// 引入工具函式const utils = require('./utils')// 引入配置檔案,也就是config/index.js檔案const config = require('../config')// 引入vue-loader的配置檔案const vueLoaderConfig = require('./vue-loader.conf')// 定義獲取絕對路徑函式function resolve (dir) {
return path.join(__dirname, '..', dir)
}// 建立eslint配置const createLintingRule = () =>
({
test: /\.(js|vue)$/, loader: 'eslint-loader', // 執行順序,前置,還有一個選項是post是後置 // 把 eslint-loader 的執行順序放到最前面,防止其它 Loader 把處理後的程式碼交給 eslint-loader 去檢查 enforce: 'pre', // 包含資料夾 include: [resolve('src'), resolve('test')], options: {
// 使用友好的eslint提示外掛 formatter: require('eslint-friendly-formatter'), // eslint報錯提示是否顯示以遮罩形式顯示在瀏覽器中 // 這裡showEslintErrorsInOverlay配置是false emitWarning: !config.dev.showEslintErrorsInOverlay
}
})module.exports = {
// 執行環境的上下文,就是實際的目錄,也就是專案根目錄 context: path.resolve(__dirname, '../'), // 入口 entry: {
app: './src/main.js'
}, // 輸出 output: {
// 路徑 這裡是根目錄下的dist path: config.build.assetsRoot, // 檔名 filename: '[name].js', publicPath: process.env.NODE_ENV === 'production' // 這裡是 /,但要上傳到github pages等會路徑不對,需要修改為./ ? config.build.assetsPublicPath // 這裡配置是 / : config.dev.assetsPublicPath
}, // Webpack 在啟動後會從配置的入口模組出發找出所有依賴的模組,Resolve 配置 Webpack 如何尋找模組所對應的檔案。 resolve: {
// 配置了這個,對應的副檔名可以省略 extensions: ['.js', '.vue', '.json'], alias: {
// 給定物件的鍵後的末尾新增 $,以表示精準匹配 node_modules/vue/dist/vue.esm.js // 引用 import Vue from 'vue'就是引入的這個檔案最後export default Vue 匯出的Vue;
// 所以這句可以以任意大寫字母命名 比如:import V from 'vue' 'vue$': 'vue/dist/vue.esm.js', // src別名 比如 :引入import HelloWorld from '@/components/HelloWorld' '@': resolve('src'),
}
}, // 定義一些檔案的轉換規則 module: {
rules: [ // 是否使用eslint 這裡配置是true ...(config.dev.useEslint ? [createLintingRule()] : []), {
test: /\.vue$/, // vue-loader中文文件:https://vue-loader-v14.vuejs.org/zh-cn/ loader: 'vue-loader', options: vueLoaderConfig
}, {
// js檔案使用babel-loader轉換 test: /\.js$/, loader: 'babel-loader', include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
}, {
// 圖片檔案使用url-loader轉換 test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, loader: 'url-loader', options: {
// 限制大小10000B(bytes)以內,轉成base64編碼的dataURL字串 limit: 10000, // 輸出路徑 img/名稱.7位hash.副檔名 name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
}, {
// 視訊檔案使用url-loader轉換 test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/, loader: 'url-loader', options: {
limit: 10000, name: utils.assetsPath('media/[name].[hash:7].[ext]')
}
}, {
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, loader: 'url-loader', options: {
limit: 10000, name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
} ]
}, // 這裡的node是一個物件,其中每個屬性都是 Node.js 全域性變數或模組的名稱,每個 value 是以下其中之一 // empty 提供空物件。 // false 什麼都不提供。 // 更多檢視 中文文件:https://webpack.docschina.org/configuration/node/ node: {
// prevent webpack from injecting useless setImmediate polyfill because Vue // source contains it (although only uses it if it's native). // 防止webpack注入一些polyfill 因為Vue已經包含了這些。 setImmediate: false, // prevent webpack from injecting mocks to Node native modules // that does not make sense for the client dgram: 'empty', fs: 'empty', net: 'empty', tls: 'empty', child_process: 'empty'
}
}
複製程式碼

build/vue-loader.conf.js vue-loader配置檔案

上文build/webpack.dev.conf.js提到引入了build/vue-loader.conf.js

這個檔案主要匯出了一份Vue-loader的配置,主要有:loaderscssSourceMapcacheBustingtransformToRequire

具體看該檔案註釋:

'use strict'const utils = require('./utils')const config = require('../config')const isProduction = process.env.NODE_ENV === 'production'const sourceMapEnabled = isProduction  // 這裡是true  ? config.build.productionSourceMap  // 這裡是true  : config.dev.cssSourceMap// 更多配置 可以檢視vue-loader中文文件:https://vue-loader-v14.vuejs.org/zh-cn/module.exports = { 
// cssLoaders 生成相應loader配置,具體看utils檔案中的cssLoader loaders: utils.cssLoaders({
// 是否開啟sourceMap,便於除錯 sourceMap: sourceMapEnabled, // 是否提取vue單檔案的css extract: isProduction
}), // 是否開啟cssSourceMap,便於除錯 cssSourceMap: sourceMapEnabled, // 這裡是true // 快取破壞,進行sourceMap debug時,設定成false很有幫助。 cacheBusting: config.dev.cacheBusting, // vue單檔案中,在模板中的圖片等資源引用轉成require的形式。以便目標資源可以由 webpack 處理。 transformToRequire: {
video: ['src', 'poster'], source: 'src', img: 'src', // 預設配置會轉換 <
img>
標籤上的 src 屬性和 SVG 的 <
image>
標籤上的 xlink:href 屬性。 image: 'xlink:href'
}
}複製程式碼

看完了這些檔案相應配置,開發環境的相關配置就串起來了。其中config/資料夾下的配置,筆者都已經註釋在build/資料夾下的對應的檔案中,所以就不單獨說明了。

那回過頭來看,package.jsonscripts中的npm run build配置,node build/build.js,其實就是用node去執行build/build.js檔案。

build/build.js npm run build 指定執行的檔案

這個檔案主要做了以下幾件事情:
1、引入build/check-versions檔案,檢查nodenpm的版本,
2、引入相關外掛和配置,其中引入了webpack生產環境的配置build/webpack.prod.conf.js
3、先控制檯輸出loading,刪除dist目錄下的檔案,開始構建,構建失敗和構建成功都給出相應的提示資訊。

具體可以檢視相應的註釋:

'use strict'// 檢查node npm的版本require('./check-versions')()process.env.NODE_ENV = 'production'// 命令列中的loadingconst ora = require('ora')// 刪除檔案或資料夾const rm = require('rimraf')// 路徑相關const path = require('path')// 控制檯輸入樣式 chalk 更多檢視:https://github.com/chalk/chalkconst chalk = require('chalk')// 引入webpackconst webpack = require('webpack')// 引入config/index.jsconst config = require('../config')// 引入 生產環境webpack配置const webpackConfig = require('./webpack.prod.conf')// 控制檯輸入開始構建loadingconst spinner = ora('building for production...')spinner.start()// 刪除原有構建輸出的目錄檔案 這裡是dist 和 staticrm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err =>
{
// 如果出錯,丟擲錯誤 if (err) throw err webpack(webpackConfig, (err, stats) =>
{
// 關閉 控制檯輸入開始構建loading spinner.stop() // 如果出錯,丟擲錯誤 if (err) throw err process.stdout.write(stats.toString({
colors: true, modules: false, children: false, // If you are using ts-loader, setting this to true will make TypeScript errors show up during build. chunks: false, chunkModules: false
}) + '\n\n') // 如果有錯,控制檯輸出構建失敗 if (stats.hasErrors()) {
console.log(chalk.red(' Build failed with errors.\n')) process.exit(1)
} // 控制檯輸出構建成功相關資訊 console.log(chalk.cyan(' Build complete.\n')) console.log(chalk.yellow( ' Tip: built files are meant to be served over an HTTP server.\n' + ' Opening index.html over file:// won\'t work.\n' ))
})
})
複製程式碼

build/check-versions 檢查nodenpm版本

上文提到build/check-versions 檢查nodenpm版本,這個檔案主要引入了一些外掛和配置,最後匯出一個函式,版本不符合預期就輸出警告。

具體檢視這個配置檔案註釋:

'use strict'// 控制檯輸入樣式 chalk 更多檢視:https://github.com/chalk/chalkconst chalk = require('chalk')// 語義化控制版本的外掛 更多檢視:https://github.com/npm/node-semverconst semver = require('semver')// package.json配置const packageConfig = require('../package.json')// shell 指令碼 Unix shell commands for Node.js 更多檢視:https://github.com/shelljs/shelljsconst shell = require('shelljs')function exec (cmd) { 
return require('child_process').execSync(cmd).toString().trim()
}const versionRequirements = [ {
name: 'node', currentVersion: semver.clean(process.version), // 這裡配置是"node": ">
= 6.0.0"
, versionRequirement: packageConfig.engines.node
}]// 需要使用npmif (shell.which('npm')) {
versionRequirements.push({
name: 'npm', currentVersion: exec('npm --version'), // 這裡配置是"npm": ">
= 3.0.0"
versionRequirement: packageConfig.engines.npm
})
}// 匯出一個檢查版本的函式module.exports = function () {
const warnings = [] for (let i = 0;
i <
versionRequirements.length;
i++) {
const mod = versionRequirements[i] // 當前版本不大於所需版本 if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) {
warnings.push(mod.name + ': ' + chalk.red(mod.currentVersion) + ' should be ' + chalk.green(mod.versionRequirement) )
}
} // 如果有警告,全部輸出到控制檯 if (warnings.length) {
console.log('') console.log(chalk.yellow('To use this template, you must update following to modules:')) console.log() for (let i = 0;
i <
warnings.length;
i++) {
const warning = warnings[i] console.log(' ' + warning)
} console.log() process.exit(1)
}
}複製程式碼

build/webpack.prod.conf.js webpack生產環境配置

上文build/build.js提到,引入了這個配置檔案。
這個檔案主要做了以下幾件事情:
1、引入一些外掛和配置,其中引入了build/webpack.base.conf.js webpack基本配置檔案,
2、用DefinePlugin定義環境,
3、合併基本配置,定義自己的配置webpackConfig,配置了一些modules下的rulesdevtools配置,output輸出配置,一些處理js、提取css、壓縮css、輸出html外掛、提取公共程式碼等的plugins
4、如果啟用gzip,再使用相應的外掛處理,
5、如果啟用了分析打包後的外掛,則用webpack-bundle-analyzer
6、最後匯出這份配置。

具體可以檢視這個檔案配置註釋:

'use strict'// 引入node路徑相關const path = require('path')// 引入utils工具函式const utils = require('./utils')// 引入webpackconst webpack = require('webpack')// 引入config/index.js配置檔案const config = require('../config')// 合併webpack配置的外掛const merge = require('webpack-merge')// 基本的webpack配置const baseWebpackConfig = require('./webpack.base.conf')// 拷貝檔案和資料夾的外掛const CopyWebpackPlugin = require('copy-webpack-plugin')// 壓縮處理HTML的外掛const HtmlWebpackPlugin = require('html-webpack-plugin')const ExtractTextPlugin = require('extract-text-webpack-plugin')// 壓縮處理css的外掛const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')// 壓縮處理js的外掛const UglifyJsPlugin = require('uglifyjs-webpack-plugin')// 用DefinePlugin定義環境const env = process.env.NODE_ENV === 'testing'  // 這裡是 { 
NODE_ENV: '"testing"'
} ? require('../config/test.env') // 這裡是 {
NODE_ENV: '"production"'
} : require('../config/prod.env')// 合併基本webpack配置const webpackConfig = merge(baseWebpackConfig, {
module: {
// 通過styleLoaders函式生成樣式的一些規則 rules: utils.styleLoaders({
// sourceMap這裡是true sourceMap: config.build.productionSourceMap, // 是否提取css到單獨的css檔案 extract: true, // 是否使用postcss usePostCSS: true
})
}, // 配置使用sourceMap true 這裡是 #source-map devtool: config.build.productionSourceMap ? config.build.devtool : false, output: {
// 這裡是根目錄下的dist path: config.build.assetsRoot, // 檔名稱 chunkhash filename: utils.assetsPath('js/[name].[chunkhash].js'), // chunks名稱 chunkhash chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
}, plugins: [ // http://vuejs.github.io/vue-loader/en/workflow/production.html // 定義具體是什麼環境 new webpack.DefinePlugin({
'process.env': env
}), // 壓縮js外掛 new UglifyJsPlugin({
uglifyOptions: {
compress: {
// 警告 warnings: false // 構建後的檔案 常用的配置還有這些 // 去除console.log 預設為false。 傳入true會丟棄對console函式的呼叫。 // drop_console: true, // 去除debugger // drop_debugger: true, // 預設為null. 你可以傳入一個名稱的陣列,而UglifyJs將會假定那些函式不會產生副作用。 // pure_funcs: [ 'console.log', 'console.log.apply' ],
}
}, // 是否開啟sourceMap 這裡是true sourceMap: config.build.productionSourceMap, // 平行處理(同時處理)加快速度 parallel: true
}), // extract css into its own file // 提取css到單獨的css檔案 new ExtractTextPlugin({
// 提取到相應的檔名 使用內容hash contenthash filename: utils.assetsPath('css/[name].[contenthash].css'), // Setting the following option to `false` will not extract CSS from codesplit chunks. // Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack. // It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`, // increasing file size: https://github.com/vuejs-templates/webpack/issues/1110 // allChunks 預設是false,true指提取所有chunks包括動態引入的元件。 allChunks: true,
}), // Compress extracted CSS. We are using this plugin so that possible // duplicated CSS from different components can be deduped. new OptimizeCSSPlugin({
// 這裡配置是true cssProcessorOptions: config.build.productionSourceMap ? {
safe: true, map: {
inline: false
}
} : {
safe: true
}
}), // generate dist index.html with correct asset hash for caching. // you can customize output by editing /index.html // see https://github.com/ampedandwired/html-webpack-plugin new HtmlWebpackPlugin({
// 輸出html名稱 filename: process.env.NODE_ENV === 'testing' ? 'index.html' // 這裡是 根目錄下的dist/index.html : config.build.index, // 使用哪個模板 template: 'index.html', // inject 預設值 true,script標籤位於html檔案的 body 底部 // body 通true, header, script 標籤位於 head 標籤內 // false 不插入生成的 js 檔案,只是單純的生成一個 html 檔案 inject: true, // 壓縮 minify: {
// 刪除註釋 removeComments: true, // 刪除空格和換行 collapseWhitespace: true, // 刪除html標籤中屬性的雙引號 removeAttributeQuotes: true // 更多配置檢視html-minifier外掛 // more options: // https://github.com/kangax/html-minifier#options-quick-reference
}, // necessary to consistently work with multiple chunks via CommonsChunkPlugin // 在chunk被插入到html之前,你可以控制它們的排序。允許的值 ‘none’ | ‘auto’ | ‘dependency’ | {function
} 預設為‘auto’. // dependency 依賴(從屬) chunksSortMode: 'dependency'
}), // keep module.id stable when vendor modules does not change // 根據程式碼內容生成普通模組的id,確保原始碼不變,moduleID不變。 new webpack.HashedModuleIdsPlugin(), // enable scope hoisting // 開啟作用域提升 webpack3新的特性,作用是讓程式碼檔案更小、執行的更快 new webpack.optimize.ModuleConcatenationPlugin(), // split vendor js into its own file // 提取公共程式碼 new webpack.optimize.CommonsChunkPlugin({
name: 'vendor', minChunks (module) {
// any required modules inside node_modules are extracted to vendor return ( module.resource &
&
/\.js$/.test(module.resource) &
&
module.resource.indexOf( path.join(__dirname, '../node_modules') ) === 0 )
}
}), // extract webpack runtime and module manifest to its own file in order to // prevent vendor hash from being updated whenever app bundle is updated // 提取公共程式碼 new webpack.optimize.CommonsChunkPlugin({
// 把公共的部分放到 manifest 中 name: 'manifest', // 傳入 `Infinity` 會馬上生成 公共chunk,但裡面沒有模組。 minChunks: Infinity
}), // This instance extracts shared chunks from code splitted chunks and bundles them // in a separate chunk, similar to the vendor chunk // see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk // 提取動態元件 new webpack.optimize.CommonsChunkPlugin({
name: 'app', // 如果設定為 `true`,一個非同步的 公共chunk 會作為 `options.name` 的子模組,和 `options.chunks` 的兄弟模組被建立。 // 它會與 `options.chunks` 並行被載入。可以通過提供想要的字串,而不是 `true` 來對輸出的檔案進行更換名稱。 async: 'vendor-async', // 如果設定為 `true`,所有 公共chunk 的子模組都會被選擇 children: true, // 最小3個,包含3,chunk的時候提取 minChunks: 3
}), // copy custom static assets // 把static資源複製到相應目錄。 new CopyWebpackPlugin([ {
from: path.resolve(__dirname, '../static'), // 這裡配置是static to: config.build.assetsSubDirectory, // 忽略.開頭的檔案。比如這裡的.gitkeep,這個檔案是指空資料夾也提交到git ignore: ['.*']
} ]) ]
})// 如果開始gzip壓縮,使用compression-webpack-plugin外掛處理。這裡配置是false// 需要使用是需要安裝 npm i compression-webpack-plugin -Dif (config.build.productionGzip) {
const CompressionWebpackPlugin = require('compression-webpack-plugin') webpackConfig.plugins.push( new CompressionWebpackPlugin({
// asset: 目標資源名稱。 [file] 會被替換成原始資源。 // [path] 會被替換成原始資源的路徑, [query] 會被替換成查詢字串。預設值是 "[path].gz[query]"。 asset: '[path].gz[query]', // algorithm: 可以是 function(buf, callback) 或者字串。對於字串來說依照 zlib 的演算法(或者 zopfli 的演算法)。預設值是 "gzip"。 algorithm: 'gzip', // test: 所有匹配該正則的資源都會被處理。預設值是全部資源。 // config.build.productionGzipExtensions 這裡是['js', 'css'] test: new RegExp( '\\.(' + config.build.productionGzipExtensions.join('|') + ')$' ), // threshold: 只有大小大於該值的資源會被處理。單位是 bytes。預設值是 0。 threshold: 10240, // minRatio: 只有壓縮率小於這個值的資源才會被處理。預設值是 0.8。 minRatio: 0.8
}) )
}// 輸出分析的外掛 執行npm run build --report// config.build.bundleAnalyzerReport這裡是 process.env.npm_config_report// build結束後會自定開啟 http://127.0.0.1:8888 連結if (config.build.bundleAnalyzerReport) {
// 更多檢視連結地址:https://www.npmjs.com/package/webpack-bundle-analyzer const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}// 當然也可以用官方提供的網站 http://webpack.github.io/analyse/#home// 執行類似 webpack --profile --json >
stats.json 命令// 把生成的構建資訊stats.json上傳即可// 最終匯出 webpackConfigmodule.exports = webpackConfig複製程式碼

至此,我們就分析完了package.json中的npm run devnpm run build兩個命令。測試相關的類似就略過吧。

npm run lint.eslintrc.js中的配置不多,更多可以檢視eslint英文文件eslint中文官網,所以也略過吧。不過提一下,把eslint整合到git工作流。可以安裝huskynpm i husky -S。安裝後,配置package.jsonscripts中,配置precommit,具體如下:

"scripts": { 
"lint": "eslint --ext .js,.vue src test/unit test/e2e/specs", "precommit": "npm run lint",
},複製程式碼

配置好後,每次git commit -m提交會檢查程式碼是否通過eslint校驗,如果沒有校驗通過則提交失敗。還可以配置prepushhusky不斷在更新,現在可能與原先的配置不太相同了,具體檢視husky github倉庫。原理就是git-hooks,pre-commit的鉤子。對shell指令碼熟悉的同學也可以自己寫一份pre-commit。複製到專案的.git/hooks/pre-commit中。不需要依賴husky包。我司就是用的shell指令碼。

最後提一下.babelrc檔案中的配置。

.babelrc babel相關配置

配置了一些轉碼規則。這裡附上兩個連結:babel英文官網babel的中文官網

具體看檔案中的配置註釋:

{ 
// presets指明轉碼的規則 "presets": [ // env項是藉助外掛babel-preset-env,下面這個配置說的是babel對es6,es7,es8進行轉碼,並且設定amd,commonjs這樣的模組化檔案,不進行轉碼 ["env", {
"modules": false, "targets": {
"browsers": [">
1%"
, "last 2 versions", "not ie <
= 8"
]
}
}], "stage-2" ], // plugins 屬性告訴 Babel 要使用哪些外掛,外掛可以控制如何轉換程式碼。 // transform-vue-jsx 表明可以在專案中使用jsx語法,會使用這個外掛轉換 "plugins": ["transform-vue-jsx", "transform-runtime"], // 在特定的環境中所執行的轉碼規則,當環境變數是下面的test就會覆蓋上面的設定 "env": {
// test 是提前設定的環境變數,如果沒有設定BABEL_ENV則使用NODE_ENV,如果都沒有設定預設就是development "test": {
"presets": ["env", "stage-2"], "plugins": ["transform-vue-jsx", "transform-es2015-modules-commonjs", "dynamic-import-node"]
}
}
}複製程式碼

檔案中presets中有配置envstage-2,可能不知道是什麼。這裡引用深入淺出webpack書中,第三章,3-1使用ES6語言 小節的一段,解釋一下。

presets 屬性告訴 Babel 要轉換的原始碼使用了哪些新的語法特性,一個 Presets 對一組新語法特性提供支援,多個 Presets 可以疊加。 Presets 其實是一組 Plugins 的集合,每一個 Plugin 完成一個新語法的轉換工作。Presets 是按照 ECMAScript 草案來組織的,通常可以分為以下三大類(書中就是說三大類,我發現就兩點~~~):
1、已經被寫入 ECMAScript 標準裡的特性,由於之前每年都有新特性被加入到標準裡,所以又可細分為:
es2015 包含在2015里加入的新特性;
es2016 包含在2016里加入的新特性;
es2017 包含在2017里加入的新特性;
es2017 包含在2017里加入的新特性;
env 包含當前所有 ECMAScript 標準裡的最新特性。
2、被社群提出來的但還未被寫入 ECMAScript 標準裡特性,這其中又分為以下四種:
stage0 只是一個美好激進的想法,有 Babel 外掛實現了對這些特性的支援,但是不確定是否會被定為標準;
stage1 值得被納入標準的特性;
stage2 該特性規範已經被起草,將會被納入標準裡;
stage3 該特性規範已經定稿,各大瀏覽器廠商和 “ 社群開始著手實現;
stage4 在接下來的一年將會加入到標準裡去。

至此,就算相對完整的分析完了Vue-cli(版本v2.9.3)搭建的webpack專案工程。希望對大家有所幫助。
專案放在筆者的github上,分析vue-cli@2.9.3 搭建的webpack專案工程。方便大家克隆下載,或者線上檢視。同時也求個star ^_^,也是對筆者的一種鼓勵和支援。
筆者知識能力有限,文章有什麼不妥之處,歡迎指出~

小結

1、分析這些,逐行註釋,還是需要一些時間的。其中有些不是很明白的地方,及時查閱相應的官方文件和外掛文件(建議看英文文件和最新的文件),不過文件沒寫明白的地方,可以多搜尋一些別人的部落格文章,相對比較清晰明瞭。
2、前端發展太快,這個Vue-cli@2.9.3 webpack版本還是v3.x,webpack現在官方版本已經是v4.12.0,相信不久後,Vue-cli也將釋出支援webpack v4.x的版本,v3.0.0已經是beta.16了。
3、後續有餘力,可能會繼續分析新版的vue-cli構建的webpack專案工程。

關於

作者:常以軒轅Rowboat若川為名混跡於江湖。前端路上 | PPT愛好者 | 所知甚少,唯善學。
個人部落格
segmentfault前端視野專欄,開通了前端視野專欄,歡迎關注
掘金專欄,歡迎關注
知乎前端視野專欄,開通了前端視野專欄,歡迎關注
github,歡迎follow~

來源:https://juejin.im/post/5b1df3d76fb9a01e6c0b439b

相關文章