由于最近在vue-cli生成的webpack模板項目的基礎上寫一個小東西,開發過程中需要改動到build和config里面一些相關的配置,所以剛好趁此機會將所有配置文件看一遍,理一理思路,也便于以后修改配置的時候不會“太折騰”。
一、文件結構
本文主要分析開發(dev)和構建(build)兩個過程涉及到的文件,故下面文件結構僅列出相應的內容。
├─build│ ├─build.js│ ├─check-versions.js│ ├─dev-client.js│ ├─dev-server.js│ ├─utils.js│ ├─vue-loader.conf.js│ ├─webpack.base.conf.js│ ├─webpack.dev.conf.js│ ├─webpack.prod.conf.js│ └─webpack.test.conf.js├─config│ ├─dev.env.js│ ├─index.js│ ├─prod.env.js│ └─test.env.js├─...└─package.json
二、指令分析
首先看package.json里面的scripts字段,
"scripts": { "dev": "node build/dev-server.js", "build": "node build/build.js", "unit": "cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run", "e2e": "node test/e2e/runner.js", "test": "npm run unit && npm run e2e", "lint": "eslint --ext .js,.vue src test/unit/specs test/e2e/specs" }測試的東西先不看,直接看”dev”和”build”。運行”npm run dev”的時候執行的是build/dev-server.js文件,運行”npm run build”的時候執行的是build/build.js文件,我們可以從這兩個文件開始進行代碼閱讀分析。
三、build文件夾分析
build/dev-server.js
首先來看執行”npm run dev”時候最先執行的build/dev-server.js文件。該文件主要完成下面幾件事情:
說明: express服務器提供靜態文件服務,不過它還使用了http-proxy-middleware,一個http請求代理的中間件。前端開發過程中需要使用到后臺的API的話,可以通過配置proxyTable來將相應的后臺請求代理到專用的API服務器。
詳情請看代碼注釋:
// 檢查NodeJS和npm的版本require('./check-versions')()// 獲取配置var config = require('../config')// 如果Node的環境變量中沒有設置當前的環境(NODE_ENV),則使用config中的配置作為當前的環境if (!process.env.NODE_ENV) { process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV)}// 一個可以調用默認軟件打開網址、圖片、文件等內容的插件// 這里用它來調用默認瀏覽器打開dev-server監聽的端口,例如:localhost:8080var opn = require('opn')var path = require('path')var express = require('express')var webpack = require('webpack')// 一個express中間件,用于將http請求代理到其他服務器// 例:localhost:8080/api/xxx --> localhost:3000/api/xxx// 這里使用該插件可以將前端開發中涉及到的請求代理到API服務器上,方便與服務器對接var proxyMiddleware = require('http-proxy-middleware')// 根據 Node 環境來引入相應的 webpack 配置var webpackConfig = process.env.NODE_ENV === 'testing' ? require('./webpack.prod.conf') : require('./webpack.dev.conf')// dev-server 監聽的端口,默認為config.dev.port設置的端口,即8080var port = process.env.PORT || config.dev.port// 用于判斷是否要自動打開瀏覽器的布爾變量,當配置文件中沒有設置自動打開瀏覽器的時候其值為 falsevar autoOpenBrowser = !!config.dev.autoOpenBrowser// 定義 HTTP 代理表,代理到 API 服務器var proxyTable = config.dev.proxyTable// 創建1個 express 實例var app = express()// 根據webpack配置文件創建Compiler對象var compiler = webpack(webpackConfig)// webpack-dev-middleware使用compiler對象來對相應的文件進行編譯和綁定// 編譯綁定后將得到的產物存放在內存中而沒有寫進磁盤// 將這個中間件交給express使用之后即可訪問這些編譯后的產品文件var devMiddleware = require('webpack-dev-middleware')(compiler, { publicPath: webpackConfig.output.publicPath, quiet: true})// webpack-hot-middleware,用于實現熱重載功能的中間件var hotMiddleware = require('webpack-hot-middleware')(compiler, { log: () => {}})// 當html-webpack-plugin提交之后通過熱重載中間件發布重載動作使得頁面重載compiler.plugin('compilation', function (compilation) { compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) { hotMiddleware.publish({ action: 'reload' }) cb() })})// 將 proxyTable 中的代理請求配置掛在到express服務器上Object.keys(proxyTable).forEach(function (context) { var options = proxyTable[context] // 格式化options,例如將'www.example.com'變成{ target: 'www.example.com' } if (typeof options === 'string') { options = { target: options } } app.use(proxyMiddleware(options.filter || context, options))})// handle fallback for HTML5 history API// 重定向不存在的URL,常用于SPAapp.use(require('connect-history-api-fallback')())// serve webpack bundle output// 使用webpack開發中間件// 即將webpack編譯后輸出到內存中的文件資源掛到express服務器上app.use(devMiddleware)// enable hot-reload and state-preserving// compilation error display// 將熱重載中間件掛在到express服務器上app.use(hotMiddleware)// serve pure static assets// 靜態資源的路徑var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory)// 將靜態資源掛到express服務器上app.use(staticPath, express.static('./static'))// 應用的地址信息,例如:http://localhost:8080var uri = 'http://localhost:' + port// webpack開發中間件合法(valid)之后輸出提示語到控制臺,表明服務器已啟動devMiddleware.waitUntilValid(function () { console.log('> Listening at ' + uri + '/n')})// 啟動express服務器并監聽相應的端口(8080)module.exports = app.listen(port, function (err) { if (err) { console.log(err) return } // when env is testing, don't need open it // 如果符合自動打開瀏覽器的條件,則通過opn插件調用系統默認瀏覽器打開對應的地址uri if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') { opn(uri) }})build/webpack.base.conf.js
從代碼中看到,dev-server使用的webpack配置來自build/webpack.dev.conf.js文件(測試環境下使用的是build/webpack.prod.conf.js,這里暫時不考慮測試環境)。而build/webpack.dev.conf.js中又引用了webpack.base.conf.js,所以這里我先分析webpack.base.conf.js。
webpack.base.conf.js主要完成了下面這些事情:
說明: 這個配置里面只配置了.js、.vue、圖片、字體等幾類文件的處理規則,如果需要處理其他文件可以在module.rules里面配置。
具體請看代碼注釋:
var path = require('path')var utils = require('./utils')var config = require('../config')var vueLoaderConfig = require('./vue-loader.conf')// 給出正確的絕對路徑function resolve (dir) { return path.join(__dirname, '..', dir)}module.exports = { // 配置webpack編譯入口 entry: { app: './src/main.js' }, // 配置webpack輸出路徑和命名規則 output: { // webpack輸出的目標文件夾路徑(例如:/dist) path: config.build.assetsRoot, // webpack輸出bundle文件命名格式 filename: '[name].js', // webpack編譯輸出的發布路徑 publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath }, // 配置模塊resolve的規則 resolve: { // 自動resolve的擴展名 extensions: ['.js', '.vue', '.json'], // resolve模塊的時候要搜索的文件夾 modules: [ resolve('src'), resolve('node_modules') ], // 創建路徑別名,有了別名之后引用模塊更方便,例如 // import Vue from 'vue/dist/vue.common.js'可以寫成 import Vue from 'vue' alias: { 'vue$': 'vue/dist/vue.common.js', 'src': resolve('src'), 'assets': resolve('src/assets'), 'components': resolve('src/components') } }, // 配置不同類型模塊的處理規則 module: { rules: [ {// 對src和test文件夾下的.js和.vue文件使用eslint-loader test: //.(js|vue)$/, loader: 'eslint-loader', enforce: "pre", include: [resolve('src'), resolve('test')], options: { formatter: require('eslint-friendly-formatter') } }, {// 對所有.vue文件使用vue-loader test: //.vue$/, loader: 'vue-loader', options: vueLoaderConfig }, {// 對src和test文件夾下的.js文件使用babel-loader test: //.js$/, loader: 'babel-loader', include: [resolve('src'), resolve('test')] }, {// 對圖片資源文件使用url-loader,query.name指明了輸出的命名規則 test: //.(png|jpe?g|gif|svg)(/?.*)?$/, loader: 'url-loader', query: { limit: 10000, name: utils.assetsPath('img/[name].[hash:7].[ext]') } }, {// 對字體資源文件使用url-loader,query.name指明了輸出的命名規則 test: //.(woff2?|eot|ttf|otf)(/?.*)?$/, loader: 'url-loader', query: { limit: 10000, name: utils.assetsPath('fonts/[name].[hash:7].[ext]') } } ] }}build/webpack.dev.conf.js
接下來看webpack.dev.conf.js,這里面在webpack.base.conf的基礎上增加完善了開發環境下面的配置,主要包括下面幾件事情:
詳情請看代碼注釋:
var utils = require('./utils')var webpack = require('webpack')var config = require('../config')// 一個可以合并數組和對象的插件var merge = require('webpack-merge')var baseWebpackConfig = require('./webpack.base.conf')// 一個用于生成HTML文件并自動注入依賴文件(link/script)的webpack插件var HtmlWebpackPlugin = require('html-webpack-plugin')// 用于更友好地輸出webpack的警告、錯誤等信息var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')// add hot-reload related code to entry chunksObject.keys(baseWebpackConfig.entry).forEach(function (name) { baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])})// 合并基礎的webpack配置module.exports = merge(baseWebpackConfig, { // 配置樣式文件的處理規則,使用styleLoaders module: { rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap }) }, // 配置Source Maps。在開發中使用cheap-module-eval-source-map更快 devtool: '#cheap-module-eval-source-map', // 配置webpack插件 plugins: [ new webpack.DefinePlugin({ 'process.env': config.dev.env }), // https://github.com/glenjamin/webpack-hot-middleware#installation--usage new webpack.HotModuleReplacementPlugin(), // 后頁面中的報錯不會阻塞,但是會在編譯結束后報錯 new webpack.NoEmitOnErrorsPlugin(), // https://github.com/ampedandwired/html-webpack-plugin new HtmlWebpackPlugin({ filename: 'index.html', template: 'index.html', inject: true }), new FriendlyErrorsPlugin() ]})build/utils.js和build/vue-loader.conf.js
前面的webpack配置文件中使用到了utils.js和vue-loader.conf.js這兩個文件,utils主要完成下面3件事:
vue-loader.conf則只配置了css加載器以及編譯css之后自動添加前綴。詳情請看代碼注釋(下面是vue-loader.conf的代碼,utils代碼里面原有的注釋已經有相應說明這里就不貼出來了):
var utils = require('./utils')var config = require('../config')var isProduction = process.env.NODE_ENV === 'production'module.exports = { // css加載器 loaders: utils.cssLoaders({ sourceMap: isProduction ? config.build.productionSourceMap : config.dev.cssSourceMap, extract: isProduction }), // 編譯css之后自動添加前綴 postcss: [ require('autoprefixer')({ browsers: ['last 2 versions'] }) ]}build/build.js
講完了開發環境下的配置,下面開始來看構建環境下的配置。執行”npm run build”的時候首先執行的是build/build.js文件,build.js主要完成下面幾件事:
說明: webpack編譯之后會輸出到配置里面指定的目標文件夾;刪除目標文件夾之后再創建是為了去除舊的內容,以免產生不可預測的影響。
詳情請看代碼注釋:
// https://github.com/shelljs/shelljs// 檢查NodeJS和npm的版本require('./check-versions')()process.env.NODE_ENV = 'production'// Elegant terminal spinnervar ora = require('ora')var path = require('path')// 用于在控制臺輸出帶顏色字體的插件var chalk = require('chalk')// 執行Unix命令行的插件var shell = require('shelljs')var webpack = require('webpack')var config = require('../config')var webpackConfig = require('./webpack.prod.conf')var spinner = ora('building for production...')spinner.start() // 開啟loading動畫// 輸出文件的目標文件夾var assetsPath = path.join(config.build.assetsRoot, config.build.assetsSubDirectory)// 遞歸刪除舊的目標文件夾shell.rm('-rf', assetsPath)// 重新創建文件夾 shell.mkdir('-p', assetsPath)shell.config.silent = true// 將static文件夾復制到輸出的目標文件夾shell.cp('-R', 'static/*', assetsPath)shell.config.silent = false// webpack編譯webpack(webpackConfig, function (err, stats) { spinner.stop() // 停止loading動畫 if (err) throw err // 沒有出錯則輸出相關信息 process.stdout.write(stats.toString({ colors: true, modules: false, children: false, chunks: false, chunkModules: false }) + '/n/n') 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/webpack.prod.conf.js
構建的時候用到的webpack配置來自webpack.prod.conf.js,該配置同樣是在webpack.base.conf基礎上的進一步完善。主要完成下面幾件事情:
說明: webpack插件里面多了丑化壓縮代碼以及抽離css文件等插件。
詳情請看代碼:
var path = require('path')var utils = require('./utils')var webpack = require('webpack')var config = require('../config')var merge = require('webpack-merge')var baseWebpackConfig = require('./webpack.base.conf')var HtmlWebpackPlugin = require('html-webpack-plugin')// 用于從webpack生成的bundle中提取文本到特定文件中的插件// 可以抽取出css,js文件將其與webpack輸出的bundle分離var ExtractTextPlugin = require('extract-text-webpack-plugin')var env = process.env.NODE_ENV === 'testing' ? require('../config/test.env') : config.build.env// 合并基礎的webpack配置var webpackConfig = merge(baseWebpackConfig, { module: { rules: utils.styleLoaders({ sourceMap: config.build.productionSourceMap, extract: true }) }, devtool: config.build.productionSourceMap ? '#source-map' : false, // 配置webpack的輸出 output: { // 編譯輸出目錄 path: config.build.assetsRoot, // 編譯輸出文件名格式 filename: utils.assetsPath('js/[name].[chunkhash].js'), // 沒有指定輸出名的文件輸出的文件名格式 chunkFilename: utils.assetsPath('js/[id].[chunkhash].js') }, // 配置webpack插件 plugins: [ // http://vuejs.github.io/vue-loader/en/workflow/production.html new webpack.DefinePlugin({ 'process.env': env }), // 丑化壓縮代碼 new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, sourceMap: true }), // 抽離css文件 new ExtractTextPlugin({ filename: 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 new HtmlWebpackPlugin({ filename: process.env.NODE_ENV === 'testing' ? 'index.html' : config.build.index, template: 'index.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 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 new webpack.optimize.CommonsChunkPlugin({ name: 'manifest', chunks: ['vendor'] }) ]})// gzip模式下需要引入compression插件進行壓縮if (config.build.productionGzip) { var CompressionWebpackPlugin = require('compression-webpack-plugin') webpackConfig.plugins.push( new CompressionWebpackPlugin({ asset: '[path].gz[query]', algorithm: 'gzip', test: new RegExp( '//.(' + config.build.productionGzipExtensions.join('|') + ')$' ), threshold: 10240, minRatio: 0.8 }) )}if (config.build.bundleAnalyzerReport) { var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin webpackConfig.plugins.push(new BundleAnalyzerPlugin())}module.exports = webpackConfigbuild/check-versions.js和build/dev-client.js
最后是build文件夾下面兩個比較簡單的文件,dev-client.js似乎沒有使用到,代碼也比較簡單,這里不多講。check-version.js完成對node和npm的版本檢測,下面是其代碼注釋:
// 用于在控制臺輸出帶顏色字體的插件var chalk = require('chalk')// 語義化版本檢查插件(The semantic version parser used by npm)var semver = require('semver')// 引入package.jsonvar packageConfig = require('../package.json')// 開辟子進程執行指令cmd并返回結果function exec (cmd) { return require('child_process').execSync(cmd).toString().trim()}// node和npm版本需求var versionRequirements = [ { name: 'node', currentVersion: semver.clean(process.version), versionRequirement: packageConfig.engines.node }, { name: 'npm', currentVersion: exec('npm --version'), versionRequirement: packageConfig.engines.npm }]module.exports = function () { var warnings = [] // 依次判斷版本是否符合要求 for (var i = 0; i < versionRequirements.length; i++) { var 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 (var i = 0; i < warnings.length; i++) { var warning = warnings[i] console.log(' ' + warning) } console.log() process.exit(1) }}四、config文件夾分析
config/index.js
config文件夾下最主要的文件就是index.js了,在這里面描述了開發和構建兩種環境下的配置,前面的build文件夾下也有不少文件引用了index.js里面的配置。下面是代碼注釋:
// see http://vuejs-templates.github.io/webpack for documentation.var path = require('path')module.exports = { // 構建產品時使用的配置 build: { // webpack的編譯環境 env: require('./prod.env'), // 編譯輸入的index.html文件 index: path.resolve(__dirname, '../dist/index.html'), // webpack輸出的目標文件夾路徑 assetsRoot: path.resolve(__dirname, '../dist'), // webpack編譯輸出的二級文件夾 assetsSubDirectory: 'static', // webpack編譯輸出的發布路徑 assetsPublicPath: '/', // 使用SourceMap 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'], // Run the build command with an extra argument to // View the bundle analyzer report after build finishes: // `npm run build --report` // Set to `true` or `false` to always turn it on or off bundleAnalyzerReport: process.env.npm_config_report }, // 開發過程中使用的配置 dev: { // webpack的編譯環境 env: require('./dev.env'), // dev-server監聽的端口 port: 8080, // 啟動dev-server之后自動打開瀏覽器 autoOpenBrowser: true, // webpack編譯輸出的二級文件夾 assetsSubDirectory: 'static', // webpack編譯輸出的發布路徑 assetsPublicPath: '/', // 請求代理表,在這里可以配置特定的請求代理到對應的API接口 // 例如將'/api/xxx'代理到'www.example.com/api/xxx' 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 }}config/dev.env.js、config/prod.env.js和config/test.env.js
這三個文件就簡單設置了環境變量而已,沒什么特別的。
五、總結
到這里對模板項目的build和config文件夾下面的內容已經基本了解,知道了在實際使用中根據自己的需求修改哪里的配置,例如,當我有需要配置代理的時候要在config/index.js里面的dev.proxyTable設置,當我修改了資源文件夾名稱static同樣需要在config/index.js里面設置。總體感覺入門了webpack,但不算真正理解。webpack的插件好多,在看代碼的過程中遇到不認識的插件都是要去查看很多文檔(github,npm或者博客),感覺實際過程中更改插件配置或者使用新插件也是需要費點心思鉆文檔和網上其他博客介紹。
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持武林網!
新聞熱點
疑難解答