vue-cli各配置文件注釋詳解

1、build.js

'use strict'
//立即執(zhí)行
require('./check-versions')()

//process是node中的global全局對象的屬性,process是node中的全局變量,env設(shè)置環(huán)境變量
process.env.NODE_ENV = 'production'
// ora是一個命令行轉(zhuǎn)圈圈動畫插件,好看用的
const ora = require('ora')
// rimraf插件是用來執(zhí)行UNIX命令rm和-rf的用來刪除文件夾和文件,清空舊的文件
const rm = require('rimraf')
// node.js路徑模塊 連接路徑,例子:path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');// 返回: '/foo/bar/baz/asdf'
const path = require('path')
//chalk插件,用來在命令行中輸入不同顏色的文字
const chalk = require('chalk')
// 引入webpack模塊使用內(nèi)置插件和webpack方法
const webpack = require('webpack')
//commonJs風(fēng)格,引入文件模塊,引入模塊分為內(nèi)置模塊與文件模塊兩種
const config = require('../config')
const webpackConfig = require('./webpack.prod.conf')
// 開啟轉(zhuǎn)圈圈動畫
const spinner = ora('building for production...')
spinner.start()
// 調(diào)用rm方法,第一個參數(shù)的結(jié)果就是 絕對/工程名/dist/static,表示刪除這個路徑下面的所有文件
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
  // 如果刪除的過程中出現(xiàn)錯誤,就拋出這個錯誤,同時程序終止
  if (err) throw err
  // 沒有錯誤,就執(zhí)行webpack編譯
  webpack(webpackConfig, (err, stats) => {
    // 這個回調(diào)函數(shù)是webpack編譯過程中執(zhí)行
    spinner.stop()
    // 如果有錯誤就拋出錯誤
    if (err) throw err
    // 沒有錯誤就執(zhí)行下面的代碼,process.stdout.write和console.log類似,輸出對象
    //process.stdout用來控制標(biāo)準(zhǔn)輸出,也就是在命令行窗口向用戶顯示內(nèi)容。它的write方法等同于console.log
    process.stdout.write(stats.toString({
      // stats對象中保存著編譯過程中的各種消息
      colors: true, // 增加控制臺顏色開關(guān)
      modules: false, // 不增加內(nèi)置模塊信息
      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èi)置模塊的信息加到包信息
    }) + '\n\n')

    if (stats.hasErrors()) {
      console.log(chalk.red('  Build failed with errors.\n'))
      process.exit(1)
    }
    // 以上就是在編譯過程中,持續(xù)打印消息 
    // 下面是編譯成功的消息
    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'
    ))
  })
})

2、check-versions.js

'use strict'
// 該文件用于檢測node和npm的版本,實現(xiàn)版本依賴
//chalk 是一個用來在命令行輸出不同顏色文字的包,可以使用chalk.yellow("想添加顏色的文字....")
//來實現(xiàn)改變文字顏色的;
const chalk = require('chalk')
//semver 的是一個語義化版本文件的npm包,其實它就是用來控制版本的;
const semver = require('semver')
const packageConfig = require('../package.json')
//一個用來執(zhí)行unix命令的包
const shell = require('shelljs')

//child_process 是Node.js提供了衍生子進(jìn)程功能的模塊,execSync()方法同步執(zhí)行一個cmd命令,
//將返回值的調(diào)用toString和trim方法
function exec(cmd) {
  return require('child_process').execSync(cmd).toString().trim()
}

const versionRequirements = [
  {
    name: 'node',
    //semver.clean()方法返回一個標(biāo)準(zhǔn)的版本號,切去掉兩邊的空格,比如semver.clean(" =v1.2.3 ")
    //返回"1.2.3",此外semver還有vaild,satisfies,gt,lt等方法,
    //這里查看https://npm.taobao.org/package/semver可以看到更多關(guān)于semver方法的內(nèi)容
    currentVersion: semver.clean(process.version), //使用semver格式化版本
    versionRequirement: packageConfig.engines.node //獲取package.json中設(shè)置的node版本的范圍
  }
]

//shell.which方法是去環(huán)境變量搜索有沒有參數(shù)這個命令
if (shell.which('npm')) {
  versionRequirements.push({
    name: 'npm',
    //執(zhí)行"npm --version"命令
    currentVersion: exec('npm --version'), // 自動調(diào)用npm --version命令,并且把參數(shù)返回給exec函數(shù),從而獲取純凈的版本號
    versionRequirement: packageConfig.engines.npm
  })
}

module.exports = function () {
  const warnings = []

  for (let i = 0; i < versionRequirements.length; i++) {
    const mod = versionRequirements[i]

    // semver.satisfies()進(jìn)行版本之間的比較
    if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) {
      //上面這個判斷就是如果版本號不符合package.json文件中指定的版本范圍,就執(zhí)行下面錯誤提示的代碼
      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)
  }
}

3、utils.js

'use strict'
// 引入nodejs路徑模塊
const path = require('path')
// 引入config目錄下的index.js配置文件
const config = require('../config')
// 引入extract-text-webpack-plugin插件,用來將css提取到單獨的css文件中
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const packageConfig = require('../package.json')
// exports其實就是一個對象,用來導(dǎo)出方法的,最終還是使用module.exports,此處導(dǎo)出assetsPath
exports.assetsPath = function (_path) {
  // 如果是生產(chǎn)環(huán)境assetsSubDirectory就是'static',否則還是'static',哈哈哈
  const assetsSubDirectory = process.env.NODE_ENV === 'production'
    ? config.build.assetsSubDirectory
    : config.dev.assetsSubDirectory
  // path.join和path.posix.join的區(qū)別就是,前者返回的是完整的路徑,后者返回的是完整路徑的相對根路徑
  // 也就是說path.join的路徑是C:a/a/b/xiangmu/b,那么path.posix.join就是b
  return path.posix.join(assetsSubDirectory, _path)
  // 所以這個方法的作用就是返回一個干凈的相對根路徑
}
// 下面是導(dǎo)出cssLoaders的相關(guān)配置
exports.cssLoaders = function (options) {
  // options如果不為null或者undefined,0,""等等就原樣,否則就是{}。在js里面,||運算符,A||B,A如果為真,直接返回A。如果為假,直接返回B(不會判斷B是什么類型)
  options = options || {}

  const cssLoader = {
    // cssLoader的基本配置
    loader: 'css-loader',
    options: {
      // 是否開啟cssmap,默認(rèn)是false
      sourceMap: options.sourceMap
    }
  }

  const postcssLoader = {
    loader: 'postcss-loader',
    options: {
      sourceMap: options.sourceMap
    }
  }

  // generate loader string to be used with extract text plugin
  function generateLoaders(loader, loaderOptions) {
    // 將上面的基礎(chǔ)cssLoader配置放在一個數(shù)組里面
    const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader]
    // 如果該函數(shù)傳遞了單獨的loader就加到這個loaders數(shù)組里面,這個loader可能是less,sass之類的
    if (loader) {
      // 加載對應(yīng)的loader
      loaders.push({
        loader: loader + '-loader',
        // Object.assign是es6的方法,主要用來合并對象的,淺拷貝
        options: Object.assign({}, loaderOptions, {
          sourceMap: options.sourceMap
        })
      })
    }

    // Extract CSS when that option is specified
    // (which is the case during production build)
    if (options.extract) {
      // 注意這個extract是自定義的屬性,可以定義在options里面,主要作用就是當(dāng)配置為true就把文件單獨提取,false表示不單獨提取,這個可以在使用的時候單獨配置,瞬間覺得vue作者好牛逼
      return ExtractTextPlugin.extract({
        use: loaders,
        fallback: 'vue-style-loader',
        publicPath: '../../',
      })
    } else {
      return ['vue-style-loader'].concat(loaders)
    }
    // 上面這段代碼就是用來返回最終讀取和導(dǎo)入loader,來處理對應(yīng)類型的文件
  }

  // https://vue-loader.vuejs.org/en/configurations/extract-css.html
  return {
    css: generateLoaders(),         // css對應(yīng) vue-style-loader 和 css-loader
    postcss: generateLoaders(),  // postcss對應(yīng) vue-style-loader 和 css-loader
    less: generateLoaders('less'),// less對應(yīng) vue-style-loader 和 less-loader
    sass: generateLoaders('sass', { indentedSyntax: true }),// sass對應(yīng) vue-style-loader 和 sass-loader
    scss: generateLoaders('sass'),  // scss對應(yīng) vue-style-loader 和 sass-loader
    stylus: generateLoaders('stylus'),// stylus對應(yīng) vue-style-loader 和 stylus-loader
    styl: generateLoaders('stylus')  // styl對應(yīng) vue-style-loader 和 styl-loader
  }
}

// Generate loaders for standalone style files (outside of .vue)
// 下面這個主要處理import這種方式導(dǎo)入的文件類型的打包,上面的exports.cssLoaders是為這一步服務(wù)的
exports.styleLoaders = function (options) {
  const output = []
  // 下面就是生成的各種css文件的loader對象
  const loaders = exports.cssLoaders(options)
  // 把每一種文件的laoder都提取出來
  for (const extension in loaders) {
    const loader = loaders[extension]
    output.push({
      // 把最終的結(jié)果都push到output數(shù)組中,大事搞定
      test: new RegExp('\\.' + extension + '$'),
      use: loader
    })
  }

  return output
}

//'node-notifier'是一個跨平臺系統(tǒng)通知的頁面,當(dāng)遇到錯誤時,它能用系統(tǒng)原生的推送方式給你推送信息
exports.createNotifierCallback = () => {
  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')
    })
  }
}

4、vue-loader.conf.js

'use strict'
// vue-loader的配置,用在webpack.base.conf.js中;
const utils = require('./utils')
const config = require('../config')
//不同環(huán)境為isProduction 賦值: 生產(chǎn)環(huán)境為true,開發(fā)環(huán)境為false
const isProduction = process.env.NODE_ENV === 'production'
//不同環(huán)境為sourceMapEnabled 賦值: 這里都為true
const sourceMapEnabled = isProduction
  ? config.build.productionSourceMap
  : config.dev.cssSourceMap

//導(dǎo)出vue-loader的配置,這里我們用了utils文件中的cssLoaders()
module.exports = {
  loaders: utils.cssLoaders({
    sourceMap: sourceMapEnabled,
    extract: isProduction
  }),
  cssSourceMap: sourceMapEnabled,
  cacheBusting: config.dev.cacheBusting,
  //transformToRequire的作用是在模板編譯的過程中,編譯器可以將某些屬性,如src轉(zhuǎn)換為require調(diào)用
  transformToRequire: {
    video: ['src', 'poster'],
    source: 'src',
    img: 'src',
    image: 'xlink:href'
  }
}

5、webpack.base.conf.js

'use strict' //js嚴(yán)格模式執(zhí)行
// 引入node.js路徑模塊
const path = require('path')
// 引入utils工具模塊,具體查看我的博客關(guān)于utils的解釋,utils主要用來處理css-loader和vue-style-loader的
const utils = require('./utils')
// 引入config目錄下的index.js配置文件,主要用來定義一些開發(fā)和生產(chǎn)環(huán)境的屬性
const config = require('../config')
// vue-loader.conf配置文件是用來解決各種css文件的,定義了諸如css,less,sass之類的和樣式有關(guān)的loader
const vueLoaderConfig = require('./vue-loader.conf')
// 返回到dir為止的絕對路徑
function resolve(dir) {
  return path.join(__dirname, '..', dir)
}

// const createLintingRule = () => ({
//   test: /\.(js|vue)$/,
//   loader: 'eslint-loader',
//   enforce: 'pre',
//   include: [resolve('src'), resolve('test')],
//   options: {
//     formatter: require('eslint-friendly-formatter'),
//     emitWarning: !config.dev.showEslintErrorsInOverlay
//   }
// })

module.exports = {
  context: path.resolve(__dirname, '../'),
  entry: {
    // 入口文件是src目錄下的
    app: './src/main.js'
  },
  output: {
    // 路徑是config目錄下的index.js中的build配置中的assetsRoot,也就是dist目錄,
    path: config.build.assetsRoot,
    filename: '[name].js', //name就是入口文件前面的key值,此處是index和admin 輸出文件名稱默認(rèn)使用原名
    //資源發(fā)布路徑  // 上線地址,也就是真正的文件引用路徑,
    publicPath: process.env.NODE_ENV === 'production'
      ? config.build.assetsPublicPath
      : config.dev.assetsPublicPath
  },
  resolve: {
    // resolve是webpack的內(nèi)置選項,也就是說當(dāng)使用 import "jquery",該如何去執(zhí)行這件事 
    // 情就是resolve配置項要做的,import jQuery from "./additional/dist/js/jquery" 這樣會很麻煩,可以起個別名簡化操作
    extensions: ['.js', '.vue', '.json'], // 省略擴(kuò)展名,也就是說.js,.vue,.json文件導(dǎo)入可以省略后綴名,這會覆蓋默認(rèn)的配置,所以要省略擴(kuò)展名在這里一定要寫上
    alias: {
      //我的理解是此處指定別名  require('vue/dist/vue.esm.js') 可以簡化為require('vue$')
      // resolve('src') 其實在這里就是項目根目錄中的src目錄,使用 import somejs from "@/some.js" 就可以導(dǎo)入指定文件,是不是很高大上
      'vue$': 'vue/dist/vue.esm.js',
      '@': resolve('src'),
    }
  },
  // module用來解析不同的模塊
  module: {
    rules: [
      // ...(config.dev.useEslint ? [createLintingRule()] : []),
      // 對vue文件使用vue-loader,該loader是vue單文件組件的實現(xiàn)核心,專門用來解析.vue文件的
      {
        test: /\.vue$/,
        loader: 'vue-loader', // 將vueLoaderConfig當(dāng)做參數(shù)傳遞給vue-loader,就可以解析文件中的css相關(guān)文件
        options: vueLoaderConfig
      },
      // 對js文件使用babel-loader轉(zhuǎn)碼,該插件是用來解析es6等代碼
      {
        test: /\.js$/,
        loader: 'babel-loader', // 指明src和test目錄下的js文件要使用該loader
        include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
      },
      // 對圖片相關(guān)的文件使用 url-loader 插件,這個插件的作用是將一個足夠小的文件生成一個64位的DataURL 
      // 可能有些老鐵還不知道 DataURL 是啥,當(dāng)一個圖片足夠小,為了避免單獨請求可以把圖片的二進(jìn)制代碼變成64位的 
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          // 限制 10000 個字節(jié)以下轉(zhuǎn)base64,以上不轉(zhuǎn)
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      //音頻 視頻類文件
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          //超過10000字節(jié)的圖片,就按照制定規(guī)則設(shè)置生成的圖片名稱,可以看到用了7位hash碼來標(biāo)記,.ext文件是一種索引式文件系統(tǒng)
          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.js全局變量或模塊的名稱,value為empty表示提供空對象
  node: {
    // prevent webpack from injecting useless setImmediate polyfill because Vue
    // source contains it (although only uses it if it's native).
    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'
  }
}

6、webpack.dev.conf.js

'use strict'//js按照嚴(yán)格模式執(zhí)行
const utils = require('./utils')//導(dǎo)入utils.js
const webpack = require('webpack')//使用webpack來使用webpack內(nèi)置插件
const config = require('../config')//config文件夾下index.js文件
const merge = require('webpack-merge')//引入webpack-merge插件用來合并webpack配置對象,也就是說可以把webpack配置文件拆分成幾個小的模塊,然后合并
const path = require('path')
const baseWebpackConfig = require('./webpack.base.conf')//導(dǎo)入webpack基本配置
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')//生成html文件
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder')//獲取port

const HOST = process.env.HOST//process.env屬性返回一個對象,包含了當(dāng)前shell的所有環(huán)境變量。這句取其中的host文件?
const PORT = process.env.PORT && Number(process.env.PORT)//獲取所有環(huán)境變量下的端口?
//合并模塊,第一個參數(shù)是webpack基本配置文件webpack.base.conf.js中的配置
const devWebpackConfig = merge(baseWebpackConfig, {
  module: {
    //創(chuàng)建模塊時匹配請求的規(guī)則數(shù)組,這里調(diào)用了utils中的配置模板styleLoaders
    rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
  },
  // cheap-module-eval-source-map is faster for development
  //debtool是開發(fā)工具選項,用來指定如何生成sourcemap文件,cheap-module-eval-source-map此款soucemap文件性價比最高
  devtool: config.dev.devtool,

  // these devServer options should be customized in /config/index.js
  devServer: {//webpack服務(wù)器配置
    clientLogLevel: 'warning',//使用內(nèi)聯(lián)模式時,在開發(fā)工具的控制臺將顯示消息,可取的值有none error warning info
    historyApiFallback: {//當(dāng)使用h5 history api時,任意的404響應(yīng)都可能需要被替代為index.html,通過historyApiFallback:true控制;通過傳入一個對象,比如使用rewrites這個選項進(jìn)一步控制
      rewrites: [
        { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
      ],
    },
    hot: true,//是否啟用webpack的模塊熱替換特性。這個功能主要是用于開發(fā)過程中,對生產(chǎn)環(huán)境無幫助。效果上就是界面無刷新更新。
    contentBase: false, // since we use CopyWebpackPlugin.這里禁用了該功能。本來是告訴服務(wù)器從哪里提供內(nèi)容,一半是本地靜態(tài)資源。
    compress: true,//一切服務(wù)是否都啟用gzip壓縮
    host: HOST || config.dev.host,//指定一個host,默認(rèn)是localhost。如果有全局host就用全局,否則就用index.js中的設(shè)置。
    port: PORT || config.dev.port,//指定端口
    open: config.dev.autoOpenBrowser,//是否在瀏覽器開啟本dev server
    overlay: config.dev.errorOverlay//當(dāng)有編譯器錯誤時,是否在瀏覽器中顯示全屏覆蓋。
      ? { warnings: false, errors: true }
      : false,
    publicPath: config.dev.assetsPublicPath,//此路徑下的打包文件可在瀏覽器中訪問
    proxy: config.dev.proxyTable,//如果你有單獨的后端開發(fā)服務(wù)器api,并且希望在同域名下發(fā)送api請求,那么代理某些URL會很有用。
    quiet: true, // necessary for FriendlyErrorsPlugin  啟用 quiet 后,除了初始啟動信息之外的任何內(nèi)容都不會被打印到控制臺。這也意味著來自 webpack 的錯誤或警告在控制臺不可見。
    watchOptions: {//webpack 使用文件系統(tǒng)(file system)獲取文件改動的通知。在某些情況下,不會正常工作。例如,當(dāng)使用 Network File System (NFS) 時。Vagrant 也有很多問題。在這些情況下使用輪詢。
      poll: config.dev.poll,//是否使用輪詢
    }
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': require('../config/dev.env')
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
    new webpack.NoEmitOnErrorsPlugin(),
    // https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({//模塊HtmlWebpackPlugin
      filename: 'index.html',//生成的文件的名稱
      template: 'index.html',//可以指定模塊html文件
      inject: true//在文檔上沒查到這個選項 不知道干嘛的。。。
    }),
    // copy custom static assets
    new CopyWebpackPlugin([//模塊CopyWebpackPlugin  將單個文件或整個文件復(fù)制到構(gòu)建目錄
      {
        from: path.resolve(__dirname, '../static'),//將static文件夾及其子文件復(fù)制到
        to: config.dev.assetsSubDirectory,
        ignore: ['.*']//這個沒翻譯好,百度翻譯看不懂,請自己查文檔。。。
      }
    ])
  ]
})
//webpack將運行由配置文件導(dǎo)出的函數(shù),并且等待promise返回,便于需要異步地加載所需的配置變量。
module.exports = new Promise((resolve, reject) => {
  portfinder.basePort = process.env.PORT || config.dev.port
  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: { //build成功的話會執(zhí)行者塊
          messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
        },
        onErrors: config.dev.notifyOnErrors //如果出錯就執(zhí)行這塊,其實是utils里面配置好的提示信息
          ? utils.createNotifierCallback()
          : undefined
      }))

      resolve(devWebpackConfig)
    }
  })
})

7、webpack.prod.conf.js

'use strict'
// 下面是引入nodejs的路徑模塊
const path = require('path')
// 下面是utils工具配置文件,主要用來處理css類文件的loader
const utils = require('./utils')
// 下面引入webpack,來使用webpack內(nèi)置插件
const webpack = require('webpack')
// 下面是config目錄下的index.js配置文件,主要用來定義了生產(chǎn)和開發(fā)環(huán)境的相關(guān)基礎(chǔ)配置
const config = require('../config')
// 下面是webpack的merger插件,主要用來處理配置對象合并的,可以將一個大的配置對象拆分成幾個小的,合并,相同的項將覆蓋
const merge = require('webpack-merge')
// 下面是webpack.base.conf.js配置文件,我其他博客文章已經(jīng)解釋過了,用來處理不同類型文件的loader
const baseWebpackConfig = require('./webpack.base.conf')
// copy-webpack-plugin使用來復(fù)制文件或者文件夾到指定的目錄的
const CopyWebpackPlugin = require('copy-webpack-plugin')
// html-webpack-plugin是生成html文件,可以設(shè)置模板,之前的文章將過了
const HtmlWebpackPlugin = require('html-webpack-plugin')
// extract-text-webpack-plugin這個插件是用來將bundle中的css等文件產(chǎn)出單獨的bundle文件的,之前也詳細(xì)講過
const ExtractTextPlugin = require('extract-text-webpack-plugin')
// optimize-css-assets-webpack-plugin插件的作用是壓縮css代碼的,還能去掉extract-text-webpack-plugin插件抽離文件產(chǎn)生的重復(fù)代碼,因為同一個css可能在多個模塊中出現(xiàn)所以會導(dǎo)致重復(fù)代碼,換句話說這兩個插件是兩兄弟
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

// 如果當(dāng)前環(huán)境變量NODE_ENV的值是testing,則導(dǎo)入 test.env.js配置文,設(shè)置env為"testing"
// 如果當(dāng)前環(huán)境變量NODE_ENV的值不是testing,則設(shè)置env為"production"
const env = process.env.NODE_ENV === 'testing'
  ? require('../config/test.env')
  : require('../config/prod.env')
// 把當(dāng)前的配置對象和基礎(chǔ)的配置對象合并
const webpackConfig = merge(baseWebpackConfig, {
  module: {
    // 下面就是把utils配置好的處理各種css類型的配置拿過來,和dev設(shè)置一樣,就是這里多了個extract: true,此項是自定義項,設(shè)置為true表示,生成獨立的文件
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true,
      usePostCSS: true
    })
  },
  // devtool開發(fā)工具,用來生成個sourcemap方便調(diào)試
  // 按理說這里不用生成sourcemap多次一舉,這里生成了source-map類型的map文件,只用于生產(chǎn)環(huán)境
  devtool: false,
  output: {
    // 打包后的文件放在dist目錄里面
    path: config.build.assetsRoot,
    // 文件名稱使用 static/js/[name].[chunkhash].js, 其中name就是main,chunkhash就是模塊的hash值,用于瀏覽器緩存的
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
    // chunkFilename是非入口模塊文件,也就是說filename文件中引用了chunckFilename
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
  },
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    // 下面是利用DefinePlugin插件,定義process.env環(huán)境變量為env
    new webpack.DefinePlugin({
      'process.env': env
    }),
    new UglifyJsPlugin({
      // UglifyJsPlugin插件是專門用來壓縮js文件的
      uglifyOptions: {
        compress: {
          warnings: false // 禁止壓縮時候的警告信息,給用戶一種vue高大上沒有錯誤的感覺
        }
      },
      // 壓縮后生成map文件
      sourceMap: config.build.productionSourceMap,
      parallel: true
    }),
    // extract css into its own file
    new ExtractTextPlugin({
      // 生成獨立的css文件,下面是生成獨立css文件的名稱
      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: true,
    }),
    // Compress extracted CSS. We are using this plugin so that possible
    // duplicated CSS from different components can be deduped.
    new OptimizeCSSPlugin({
      // 壓縮css文件
      cssProcessorOptions: false
    }),
    // 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'
        : 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
      // 分類要插到html頁面的模塊
      chunksSortMode: 'dependency'
    }),
    // keep module.id stable when vendor modules does not change
    new webpack.HashedModuleIdsPlugin(),
    // enable scope hoisting
    new webpack.optimize.ModuleConcatenationPlugin(),
    // split vendor js into its own file
    // 下面的插件是將打包后的文件中的第三方庫文件抽取出來,便于瀏覽器緩存,提高程序的運行速度
    new webpack.optimize.CommonsChunkPlugin({
      // common 模塊的名稱
      name: 'vendor',
      minChunks(module) {
        // any required modules inside node_modules are extracted to vendor
        // 將所有依賴于node_modules下面文件打包到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
    // 把webpack的runtime代碼和module manifest代碼提取到manifest文件中,防止修改了代碼但是沒有修改第三方庫文件導(dǎo)致第三方庫文件也打包的問題
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      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',
      async: 'vendor-async',
      children: true,
      minChunks: 3
    }),

    // copy custom static assets
    // 下面是復(fù)制文件的插件,我認(rèn)為在這里并不是起到復(fù)制文件的作用,而是過濾掉打包過程中產(chǎn)生的以.開頭的文件
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.build.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})

if (config.build.productionGzip) {
  // 開啟Gzi壓縮打包后的文件,老鐵們知道這個為什么還能壓縮嗎??,就跟你打包壓縮包一樣,把這個壓縮包給瀏覽器,瀏覽器自動解壓的
  // 你要知道,vue-cli默認(rèn)將這個神奇的功能禁用掉的,理由是Surge 和 Netlify 靜態(tài)主機(jī)默認(rèn)幫你把上傳的文件gzip了
  const CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp( // 這里是把js和css文件壓縮
        '\\.(' +
        config.build.productionGzipExtensions.join('|') +
        ')$'
      ),
      threshold: 10240,
      minRatio: 0.8
    })
  )
}

if (config.build.bundleAnalyzerReport) {
  // 打包編譯后的文件打印出詳細(xì)的文件信息,vue-cli默認(rèn)把這個禁用了,個人覺得還是有點用的,可以自行配置
  const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = webpackConfig

8、config文件下的index.js:

'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.
// path是node.js的路徑模塊,用來處理路徑統(tǒng)一的問題
const path = require('path')

module.exports = {
  // 引入當(dāng)前目錄下的dev.env.js,用來指明開發(fā)環(huán)境
  dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {}, // 下面是代理表,作用是用來,建一個虛擬api服務(wù)器用來代理本機(jī)的請求,只能用于開發(fā)模式

    // Various Dev Server settings
    host: 'localhost', // can be overwritten by process.env.HOST
    // 下面是dev-server的端口號,可以自行更改
    port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    autoOpenBrowser: false, // 下面表示是否自定代開瀏覽器
    errorOverlay: true,
    notifyOnErrors: true,
    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-

    // Use Eslint Loader?
    // If true, your code will be linted during bundling and
    // linting errors and warnings will be shown in the console.
    useEslint: true,
    // If true, eslint errors and warnings will also be shown in the error overlay
    // in the browser.
    showEslintErrorsInOverlay: false,

    /**
     * Source Maps
     */

    // https://webpack.js.org/configuration/devtool/#development
    devtool: 'cheap-module-eval-source-map',

    // If you have problems debugging vue-files in devtools,
    // set this to false - it *may* help
    // https://vue-loader.vuejs.org/en/options.html#cachebusting
    cacheBusting: true,

    cssSourceMap: true
  },

  build: {
    // 下面是build也就是生產(chǎn)編譯環(huán)境下的一些配置
    // Template for index.html
    index: path.resolve(__dirname, '../dist/index.html'),

    // Paths
    assetsRoot: path.resolve(__dirname, '../dist'), // 下面定義的是靜態(tài)資源的根目錄 也就是dist目錄
    assetsSubDirectory: 'static', // 下面定義的是靜態(tài)資源根目錄的子目錄static,也就是dist目錄下面的static
    assetsPublicPath: './', // 下面定義的是靜態(tài)資源的公開路徑,也就是真正的引用路徑

    /**
     * Source Maps
     */
    // 下面定義是否生成生產(chǎn)環(huán)境的sourcmap,sourcmap是用來debug編譯后文件的,通過映射到編譯前文件來實現(xiàn)
    productionSourceMap: true,
    // https://webpack.js.org/configuration/devtool/#production
    devtool: '#source-map',

    // 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
    productionGzip: false, // 下面是是否在生產(chǎn)環(huán)境中壓縮代碼,如果要壓縮必須安裝compression-webpack-plugin
    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
    // 下面是用來開啟編譯完成后的報告,可以通過設(shè)置值為true和false來開啟或關(guān)閉 
    // 下面的process.env.npm_config_report表示定義的一個npm_config_report環(huán)境變量,可以自行設(shè)置
    bundleAnalyzerReport: process.env.npm_config_report
  }
}

9、.eslintrc.js

// https://eslint.org/docs/user-guide/configuring

module.exports = {
  //此項是用來告訴eslint找當(dāng)前配置文件不能往父級查找
  root: true,
  //此項是用來指定eslint解析器的,解析器必須符合規(guī)則,babel-eslint解析器是對babel解析器的包裝使其與ESLint解析
  parserOptions: {
    parser: 'babel-eslint'
  },
  //此項指定環(huán)境的全局變量,下面的配置指定為瀏覽器環(huán)境
  env: {
    browser: true,
  },
  extends: [
    // https://github.com/vuejs/eslint-plugin-vue#priority-a-essential-error-prevention
    // consider switching to `plugin:vue/strongly-recommended` or `plugin:vue/recommended` for stricter rules.
    'plugin:vue/essential',
    // https://github.com/standard/standard/blob/master/docs/RULES-en.md
    // 此項是用來配置標(biāo)準(zhǔn)的js風(fēng)格,就是說寫代碼的時候要規(guī)范的寫,如果你使用vs-code我覺得應(yīng)該可以避免出錯
    'standard'
  ],
  // required to lint *.vue files
  // 此項是用來提供插件的,插件名稱省略了eslint-plugin-,下面這個配置是用來規(guī)范html的
  plugins: [
    'vue'
  ],
  // add your custom rules here
  // 下面這些rules是用來設(shè)置從插件來的規(guī)范代碼的規(guī)則,使用必須去掉前綴eslint-plugin-
  // 主要有如下的設(shè)置規(guī)則,可以設(shè)置字符串也可以設(shè)置數(shù)字,兩者效果一致
  // "off" -> 0 關(guān)閉規(guī)則
  // "warn" -> 1 開啟警告規(guī)則
  //"error" -> 2 開啟錯誤規(guī)則
  // 了解了上面這些,下面這些代碼相信也看的明白了
  rules: {
    // allow async-await
    'generator-star-spacing': 'off',
    // allow debugger during development
    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
  }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 4.25《運營之光 我的互聯(lián)網(wǎng)運營方法論與自白》 【day44盈盈】 新進(jìn)入一個行業(yè)后,第一要緊的事情就是,一定得...
    蘇小盈閱讀 141評論 0 0

友情鏈接更多精彩內(nèi)容