溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

詳解vue2.0腳手架的webpack 配置文件分析

發(fā)布時間:2020-09-11 12:32:23 來源:腳本之家 閱讀:231 作者:lamianT 欄目:web開發(fā)

前言

作為 Vue 的使用者我們對于 vue-cli 都很熟悉,但是對它的 webpack 配置我們可能關(guān)注甚少,今天我們?yōu)榇蠹規(guī)?vue-cli#2.0 的 webpack 配置分析

vue-cli 的簡介、安裝我們不在這里贅述,對它還不熟悉的同學(xué)可以直接訪問 vue-cli 查看

目錄結(jié)構(gòu)

.
├── README.md
├── build
│  ├── build.js
│  ├── check-versions.js
│  ├── dev-client.js
│  ├── dev-server.js
│  ├── utils.js
│  ├── webpack.base.conf.js
│  ├── webpack.dev.conf.js
│  └── webpack.prod.conf.js
├── config
│  ├── dev.env.js
│  ├── index.js
│  └── prod.env.js
├── index.html
├── package.json
├── src
│  ├── App.vue
│  ├── assets
│  │  └── logo.png
│  ├── components
│  │  └── Hello.vue
│  └── main.js
└── static

本篇文章的主要關(guān)注點在

build - 編譯任務(wù)的代碼

config - webpack 的配置文件

package.json - 項目的基本信息

入口

從 package.json 中我們可以看到

"scripts": {
  "dev": "node build/dev-server.js",
  "build": "node build/build.js",
  "lint": "eslint --ext .js,.vue src"
}

當(dāng)我們執(zhí)行 npm run dev / npm run build 時運行的是 node build/dev-server.js 或 node build/build.js

dev-server.js

讓我們先從 build/dev-server.js 入手

// 檢查 Node 和 npm 版本
require('./check-versions')()

// 獲取 config/index.js 的默認配置
var config = require('../config')

// 如果 Node 的環(huán)境無法判斷當(dāng)前是 dev / product 環(huán)境
// 使用 config.dev.env.NODE_ENV 作為當(dāng)前的環(huán)境

if (!process.env.NODE_ENV) process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV)

// 使用 NodeJS 自帶的文件路徑工具
var path = require('path')

// 使用 express
var express = require('express')

// 使用 webpack
var webpack = require('webpack')

// 一個可以強制打開瀏覽器并跳轉(zhuǎn)到指定 url 的插件
var opn = require('opn')

// 使用 proxyTable
var proxyMiddleware = require('http-proxy-middleware')

// 使用 dev 環(huán)境的 webpack 配置
var webpackConfig = require('./webpack.dev.conf')

// default port where dev server listens for incoming traffic

// 如果沒有指定運行端口,使用 config.dev.port 作為運行端口
var port = process.env.PORT || config.dev.port

// Define HTTP proxies to your custom API backend
// https://github.com/chimurai/http-proxy-middleware

// 使用 config.dev.proxyTable 的配置作為 proxyTable 的代理配置
var proxyTable = config.dev.proxyTable

// 使用 express 啟動一個服務(wù)
var app = express()

// 啟動 webpack 進行編譯
var compiler = webpack(webpackConfig)

// 啟動 webpack-dev-middleware,將 編譯后的文件暫存到內(nèi)存中
var devMiddleware = require('webpack-dev-middleware')(compiler, {
 publicPath: webpackConfig.output.publicPath,
 stats: {
  colors: true,
  chunks: false
 }
})

// 啟動 webpack-hot-middleware,也就是我們常說的 Hot-reload
var hotMiddleware = require('webpack-hot-middleware')(compiler)
// force page reload when html-webpack-plugin template changes
compiler.plugin('compilation', function (compilation) {
 compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
  hotMiddleware.publish({ action: 'reload' })
  cb()
 })
})

// proxy api requests
// 將 proxyTable 中的請求配置掛在到啟動的 express 服務(wù)上
Object.keys(proxyTable).forEach(function (context) {
 var options = proxyTable[context]
 if (typeof options === 'string') {
  options = { target: options }
 }
 app.use(proxyMiddleware(context, options))
})

// handle fallback for HTML5 history API
// 使用 connect-history-api-fallback 匹配資源,如果不匹配就可以重定向到指定地址
app.use(require('connect-history-api-fallback')())

// serve webpack bundle output
// 將暫存到內(nèi)存中的 webpack 編譯后的文件掛在到 express 服務(wù)上
app.use(devMiddleware)

// enable hot-reload and state-preserving
// compilation error display
// 將 Hot-reload 掛在到 express 服務(wù)上
app.use(hotMiddleware)

// serve pure static assets
// 拼接 static 文件夾的靜態(tài)資源路徑
var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory)
// 為靜態(tài)資源提供響應(yīng)服務(wù)
app.use(staticPath, express.static('./static'))

// 讓我們這個 express 服務(wù)監(jiān)聽 port 的請求,并且將此服務(wù)作為 dev-server.js 的接口暴露
module.exports = app.listen(port, function (err) {
 if (err) {
  console.log(err)
  return
 }
 var uri = 'http://localhost:' + port
 console.log('Listening at ' + uri + '\n')

 // when env is testing, don't need open it
 // 如果不是測試環(huán)境,自動打開瀏覽器并跳到我們的開發(fā)地址
 if (process.env.NODE_ENV !== 'testing') {
  opn(uri)
 }
})

webpack.dev.conf.js

剛剛我們在 dev-server.js 中用到了 webpack.dev.conf.js 和 index.js,我們先來看一下 webpack.dev.conf.js

// 同樣的使用了 config/index.js
var config = require('../config') 

// 使用 webpack
var webpack = require('webpack') 

// 使用 webpack 配置合并插件
var merge = require('webpack-merge') 

// 使用一些小工具
var utils = require('./utils') 

// 加載 webpack.base.conf
var baseWebpackConfig = require('./webpack.base.conf') 

// 使用 html-webpack-plugin 插件,這個插件可以幫我們自動生成 html 并且注入到 .html 文件中
var HtmlWebpackPlugin = require('html-webpack-plugin') 

// add hot-reload related code to entry chunks
// 將 Hol-reload 相對路徑添加到 webpack.base.conf 的 對應(yīng) entry 前
Object.keys(baseWebpackConfig.entry).forEach(function (name) {
 baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
})

// 將我們 webpack.dev.conf.js 的配置和 webpack.base.conf.js 的配置合并
module.exports = merge(baseWebpackConfig, {
 module: {
  // 使用 styleLoaders
  loaders: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap })
 },
 // eval-source-map is faster for development
 // 使用 #eval-source-map 模式作為開發(fā)工具,此配置可參考 DDFE 往期文章詳細了解
 devtool: '#eval-source-map',
 plugins: [

  // definePlugin 接收字符串插入到代碼當(dāng)中, 所以你需要的話可以寫上 JS 的字符串
  new webpack.DefinePlugin({
   'process.env': config.dev.env
  }),
  // https://github.com/glenjamin/webpack-hot-middleware#installation--usage
  new webpack.optimize.OccurenceOrderPlugin(),

  // HotModule 插件在頁面進行變更的時候只會重回對應(yīng)的頁面模塊,不會重繪整個 html 文件
  new webpack.HotModuleReplacementPlugin(),

  // 使用了 NoErrorsPlugin 后頁面中的報錯不會阻塞,但是會在編譯結(jié)束后報錯
  new webpack.NoErrorsPlugin(),
  // https://github.com/ampedandwired/html-webpack-plugin

  // 將 index.html 作為入口,注入 html 代碼后生成 index.html文件
  new HtmlWebpackPlugin({
   filename: 'index.html',
   template: 'index.html',
   inject: true
  })
 ]
})

webpack.base.conf.js

我們看到在 webpack.dev.conf.js 中又引入了 webpack.base.conf.js, 它看起來很重要的樣子,所以我們只能在下一章來看看 config/index.js 了 (攤手)

// 使用 NodeJS 自帶的文件路徑插件
var path = require('path') 

// 引入 config/index.js
var config = require('../config') 

// 引入一些小工具
var utils = require('./utils') 

// 拼接我們的工作區(qū)路徑為一個絕對路徑
var projectRoot = path.resolve(__dirname, '../') 

// 將 NodeJS 環(huán)境作為我們的編譯環(huán)境
var env = process.env.NODE_ENV

// check env & config/index.js to decide weither to enable CSS Sourcemaps for the
// various preprocessor loaders added to vue-loader at the end of this file

// 是否在 dev 環(huán)境下開啟 cssSourceMap ,在 config/index.js 中可配置
var cssSourceMapDev = (env === 'development' && config.dev.cssSourceMap)

// 是否在 production 環(huán)境下開啟 cssSourceMap ,在 config/index.js 中可配置
var cssSourceMapProd = (env === 'production' && config.build.productionSourceMap)

// 最終是否使用 cssSourceMap
var useCssSourceMap = cssSourceMapDev || cssSourceMapProd

module.exports = {
 entry: {
   // 編譯文件入口
  app: './src/main.js' 
 },
 output: {
   // 編譯輸出的根路徑
  path: config.build.assetsRoot, 
  // 正式發(fā)布環(huán)境下編譯輸出的發(fā)布路徑
  publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath, 
  // 編譯輸出的文件名
  filename: '[name].js' 
 },
 resolve: {
  // 自動補全的擴展名
  extensions: ['', '.js', '.vue'],
  // 不進行自動補全或處理的文件或者文件夾
  fallback: [path.join(__dirname, '../node_modules')],
  alias: {
  // 默認路徑代理,例如 import Vue from 'vue',會自動到 'vue/dist/vue.common.js'中尋找
   'vue': 'vue/dist/vue.common.js',
   'src': path.resolve(__dirname, '../src'),
   'assets': path.resolve(__dirname, '../src/assets'),
   'components': path.resolve(__dirname, '../src/components')
  }
 },
 resolveLoader: {
  fallback: [path.join(__dirname, '../node_modules')]
 },
 module: {
  preLoaders: [
   // 預(yù)處理的文件及使用的 loader
   {
    test: /\.vue$/,
    loader: 'eslint',
    include: projectRoot,
    exclude: /node_modules/
   },
   {
    test: /\.js$/,
    loader: 'eslint',
    include: projectRoot,
    exclude: /node_modules/
   }
  ],
  loaders: [
   // 需要處理的文件及使用的 loader
   {
    test: /\.vue$/,
    loader: 'vue'
   },
   {
    test: /\.js$/,
    loader: 'babel',
    include: projectRoot,
    exclude: /node_modules/
   },
   {
    test: /\.json$/,
    loader: 'json'
   },
   {
    test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
    loader: 'url',
    query: {
     limit: 10000,
     name: utils.assetsPath('img/[name].[hash:7].[ext]')
    }
   },
   {
    test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
    loader: 'url',
    query: {
     limit: 10000,
     name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
    }
   }
  ]
 },
 eslint: {
  // eslint 代碼檢查配置工具
  formatter: require('eslint-friendly-formatter')
 },
 vue: {
  // .vue 文件配置 loader 及工具 (autoprefixer)
  loaders: utils.cssLoaders({ sourceMap: useCssSourceMap }),
  postcss: [
   require('autoprefixer')({
    browsers: ['last 2 versions']
   })
  ]
 }
}

config/index.js

終于分析完了 webpack.base.conf.js,來讓我們看一下 config/index.js

index.js 中有 dev 和 production 兩種環(huán)境的配置

// see http://vuejs-templates.github.io/webpack for documentation.
// 不再重復(fù)介紹了 ...
var path = require('path')

module.exports = {
 // production 環(huán)境
 build: { 
   // 使用 config/prod.env.js 中定義的編譯環(huán)境
  env: require('./prod.env'), 
  index: path.resolve(__dirname, '../dist/index.html'), // 編譯輸入的 index.html 文件
  // 編譯輸出的靜態(tài)資源根路徑
  assetsRoot: path.resolve(__dirname, '../dist'), 
  // 編譯輸出的二級目錄
  assetsSubDirectory: 'static', 
  // 編譯發(fā)布上線路徑的根目錄,可配置為資源服務(wù)器域名或 CDN 域名
  assetsPublicPath: '/', 
  // 是否開啟 cssSourceMap
  productionSourceMap: true, 
  // Gzip off by default as many popular static hosts such as
  // Surge or Netlify already gzip all static assets for you.
  // Before setting to `true`, make sure to:
  // npm install --save-dev compression-webpack-plugin
  // 是否開啟 gzip
  productionGzip: false, 
  // 需要使用 gzip 壓縮的文件擴展名
  productionGzipExtensions: ['js', 'css'] 
 },
 // dev 環(huán)境
 dev: { 
   // 使用 config/dev.env.js 中定義的編譯環(huán)境
  env: require('./dev.env'), 
  // 運行測試頁面的端口
  port: 8080, 
  // 編譯輸出的二級目錄
  assetsSubDirectory: 'static', 
  // 編譯發(fā)布上線路徑的根目錄,可配置為資源服務(wù)器域名或 CDN 域名
  assetsPublicPath: '/', 
  // 需要 proxyTable 代理的接口(可跨域)
  proxyTable: {}, 
  // CSS Sourcemaps off by default because relative paths are "buggy"
  // with this option, according to the CSS-Loader README
  // (https://github.com/webpack/css-loader#sourcemaps)
  // In our experience, they generally work as expected,
  // just be aware of this issue when enabling this option.
  // 是否開啟 cssSourceMap
  cssSourceMap: false 
 }
}

至此,我們的 npm run dev 命令就講解完畢,下面讓我們來看一看執(zhí)行 npm run build 命令時發(fā)生了什么 ~

build.js

// https://github.com/shelljs/shelljs

// 檢查 Node 和 npm 版本
require('./check-versions')() 

// 使用了 shelljs 插件,可以讓我們在 node 環(huán)境的 js 中使用 shell
require('shelljs/global') 
env.NODE_ENV = 'production'

// 不再贅述
var path = require('path') 

// 加載 config.js
var config = require('../config') 

// 一個很好看的 loading 插件
var ora = require('ora') 

// 加載 webpack
var webpack = require('webpack') 

// 加載 webpack.prod.conf
var webpackConfig = require('./webpack.prod.conf') 

// 輸出提示信息 ~ 提示用戶請在 http 服務(wù)下查看本頁面,否則為空白頁
console.log(
 ' Tip:\n' +
 ' Built files are meant to be served over an HTTP server.\n' +
 ' Opening index.html over file:// won\'t work.\n'
)

// 使用 ora 打印出 loading + log
var spinner = ora('building for production...') 
// 開始 loading 動畫
spinner.start() 

// 拼接編譯輸出文件路徑
var assetsPath = path.join(config.build.assetsRoot, config.build.assetsSubDirectory)
// 刪除這個文件夾 (遞歸刪除)
rm('-rf', assetsPath)
// 創(chuàng)建此文件夾 
mkdir('-p', assetsPath)
// 復(fù)制 static 文件夾到我們的編譯輸出目錄
cp('-R', 'static/*', assetsPath)

// 開始 webpack 的編譯
webpack(webpackConfig, function (err, stats) {
 // 編譯成功的回調(diào)函數(shù)
 spinner.stop()
 if (err) throw err
 process.stdout.write(stats.toString({
  colors: true,
  modules: false,
  children: false,
  chunks: false,
  chunkModules: false
 }) + '\n')
})

webpack.prod.conf.js

// 不再贅述
var path = require('path')

// 加載 confi.index.js
var config = require('../config')

// 使用一些小工具
var utils = require('./utils') 

// 加載 webpack
var webpack = require('webpack') 

// 加載 webpack 配置合并工具
var merge = require('webpack-merge') 

// 加載 webpack.base.conf.js
var baseWebpackConfig = require('./webpack.base.conf') 

// 一個 webpack 擴展,可以提取一些代碼并且將它們和文件分離開
// 如果我們想將 webpack 打包成一個文件 css js 分離開,那我們需要這個插件
var ExtractTextPlugin = require('extract-text-webpack-plugin')

// 一個可以插入 html 并且創(chuàng)建新的 .html 文件的插件
var HtmlWebpackPlugin = require('html-webpack-plugin')
var env = config.build.env

// 合并 webpack.base.conf.js
var webpackConfig = merge(baseWebpackConfig, {
 module: {
  // 使用的 loader
  loaders: utils.styleLoaders({ sourceMap: config.build.productionSourceMap, extract: true })
 },
 // 是否使用 #source-map 開發(fā)工具,更多信息可以查看 DDFE 往期文章
 devtool: config.build.productionSourceMap ? '#source-map' : false,
 output: {
  // 編譯輸出目錄
  path: config.build.assetsRoot,
  // 編譯輸出文件名
  // 我們可以在 hash 后加 :6 決定使用幾位 hash 值
  filename: utils.assetsPath('js/[name].[chunkhash].js'), 
  // 沒有指定輸出名的文件輸出的文件名
  chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
 },
 vue: {
  // 編譯 .vue 文件時使用的 loader
  loaders: utils.cssLoaders({
   sourceMap: config.build.productionSourceMap,
   extract: true
  })
 },
 plugins: [
  // 使用的插件
  // http://vuejs.github.io/vue-loader/en/workflow/production.html
  // definePlugin 接收字符串插入到代碼當(dāng)中, 所以你需要的話可以寫上 JS 的字符串
  new webpack.DefinePlugin({
   'process.env': env
  }),
  // 壓縮 js (同樣可以壓縮 css)
  new webpack.optimize.UglifyJsPlugin({
   compress: {
    warnings: false
   }
  }),
  new webpack.optimize.OccurrenceOrderPlugin(),
  // extract css into its own file
  // 將 css 文件分離出來
  new ExtractTextPlugin(utils.assetsPath('css/[name].[contenthash].css')),
  // 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
  // 輸入輸出的 .html 文件
  new HtmlWebpackPlugin({
   filename: config.build.index,
   template: 'index.html',
   // 是否注入 html
   inject: true, 
   // 壓縮的方式
   minify: { 
    removeComments: true,
    collapseWhitespace: true,
    removeAttributeQuotes: true
    // more options:
    // https://github.com/kangax/html-minifier#options-quick-reference
   },
   // necessary to consistently work with multiple chunks via CommonsChunkPlugin
   chunksSortMode: 'dependency'
  }),
  // split vendor js into its own file
  // 沒有指定輸出文件名的文件輸出的靜態(tài)文件名
  new webpack.optimize.CommonsChunkPlugin({
   name: 'vendor',
   minChunks: function (module, count) {
    // 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
  // 沒有指定輸出文件名的文件輸出的靜態(tài)文件名
  new webpack.optimize.CommonsChunkPlugin({
   name: 'manifest',
   chunks: ['vendor']
  })
 ]
})

// 開啟 gzip 的情況下使用下方的配置
if (config.build.productionGzip) {
 // 加載 compression-webpack-plugin 插件
 var CompressionWebpackPlugin = require('compression-webpack-plugin')
 // 向webpackconfig.plugins中加入下方的插件
 var reProductionGzipExtensions = '\\.(' + config.build.productionGzipExtensions.join('|') + '$)'
 webpackConfig.plugins.push(
  // 使用 compression-webpack-plugin 插件進行壓縮
  new CompressionWebpackPlugin({
   asset: '[path].gz[query]',
   algorithm: 'gzip',
   test: new RegExp(reProductionGzipExtensions), // 注:此處因有代碼格式化的bug,與源碼有差異
   threshold: 10240,
   minRatio: 0.8
  })
 )
}

module.exports = webpackConfig

總結(jié)

 vue2.0腳手架的webpack 配置文件分析借此回顧下,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI