Vue、webpack中默認的config.js、index.js 配置詳情

在vue.js 框架搭建好後,其vue-cli 自動構建的目錄裏面相關環境變量及其基本變量配置,以下代碼所示:javascript

複製代碼
module.exports = {
 build: {
    index: path.resolve(__dirname, '../dist/index.html'),
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    productionSourceMap: true,
    devtool: '#source-map',
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],

    bundleAnalyzerReport: process.env.npm_config_report
  },
}
複製代碼

build 各參數含義:css

       index:必須是本地文件系統上的絕對路徑,index.html (帶着插入的資源路徑) 會被生成.html

       assetsRoot:指向包含應用程序的全部靜態資產的根目錄。vue

       assetsSubDirectory:存放編譯出來的資源文件,static/ 目錄下的文件會在構建過程當中直接拷貝到這個目錄下。java

       assetsPublicPath:資源的根目錄,這個是經過http服務器運行的url路徑。在大多數狀況下,這個是根目錄(/)。若是你的後臺框架對靜態資源url前綴有要求,你僅須要改變這個參數。在內部,這個是被webpack當作output.publicPath來處理的。node

                                  後臺有要求的話通常要加上./ 或者根據具體目錄添加,否則引用不到靜態資源webpack

       productionSourceMap:構建生產環境版本是是否開啓source map.git

       productionGzip:是否開啓gzip.github

       productionGzipExtensions:須要使用Gzip 壓縮的文件擴展名.web

       bundleAnalyzerReport:檢測包的狀況,在config/index.js中一個相關插件叫作bundleAnalyzerReport,當打包輸入npm run build --report,就能夠在打包的同時查看每一個打包生成的js,查看裏面相關庫的構成,以便咱們進行相關的刪減,即庫太大,是否可用本身實                                           現,有的庫是否有必要,能否進行刪除.

     

      項目中配置的config/index.js,有dev和production兩種環境的配置 如下介紹的是production環境下的webpack配置的理解

複製代碼
  var path = require('path')
  
  module.exports = {
    build: { // production 環境
      env: require('./prod.env'), // 使用 config/prod.env.js 中定義的編譯環境
      index: path.resolve(__dirname, '../dist/index.html'), // 編譯輸入的 index.html 文件
      assetsRoot: path.resolve(__dirname, '../dist'), // 編譯輸出的靜態資源路徑
      assetsSubDirectory: 'static', // 編譯輸出的二級目錄
      assetsPublicPath: '/', // 編譯發佈的根目錄,可配置爲資源服務器域名或 CDN 域名
     productionSourceMap: true, // 是否開啓 cssSourceMap
     // 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, // 是否開啓 gzip
     productionGzipExtensions: ['js', 'css'] // 須要使用 gzip 壓縮的文件擴展名
   },
   dev: { // dev 環境
     env: require('./dev.env'), // 使用 config/dev.env.js 中定義的編譯環境
     port: 8080, // 運行測試頁面的端口
     assetsSubDirectory: 'static', // 編譯輸出的二級目錄
     assetsPublicPath: '/', // 編譯發佈的根目錄,可配置爲資源服務器域名或 CDN 域名
     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: false // 是否開啓 cssSourceMap
   }
 }
複製代碼

    下面是Vue中的build/webpack.base.conf.js

複製代碼
//引入依賴模塊
var path = require('path')
var config = require('../config') // 獲取配置
var utils = require('./utils')
var projectRoot = path.resolve(__dirname, '../')
 
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
var cssSourceMapDev = (env === 'development' && config.dev.cssSourceMap)/* 是否在 dev 環境下開啓 cssSourceMap ,在 config/index.js 中可配置 */
var cssSourceMapProd = (env === 'production' && config.build.productionSourceMap)/* 是否在 production 環境下開啓 cssSourceMap ,在 config/index.js 中可配置 */
var useCssSourceMap = cssSourceMapDev || cssSourceMapProd /* 最終是否使用 cssSourceMap */
 
module.exports = {
  entry: {   // 配置webpack編譯入口
    app: './src/main.js' 
  },
  output: {    // 配置webpack輸出路徑和命名規則
    path: config.build.assetsRoot, // webpack輸出的目標文件夾路徑(例如:/dist)
    publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath,  // webpack編譯輸出的發佈路徑(判斷是正式環境或者開發環境等)
    filename: '[name].js'   // webpack輸出bundle文件命名格式,基於文件的md5生成Hash名稱的script來防止緩存
  },
  resolve: {
    extensions: ['', '.js', '.vue', '.scss'],  //自動解析肯定的拓展名,使導入模塊時不帶拓展名
    fallback: [path.join(__dirname, '../node_modules')],
    alias: {  // 建立import或require的別名,一些經常使用的,路徑長的均可以用別名
      'vue$': 'vue/dist/vue',
      'src': path.resolve(__dirname, '../src'),
      'assets': path.resolve(__dirname, '../src/assets'),
      'components': path.resolve(__dirname, '../src/components'),
      'scss_vars': path.resolve(__dirname, '../src/styles/vars.scss')
    }
  },
  resolveLoader: {
    fallback: [path.join(__dirname, '../node_modules')]
  },
  module: {
    loaders: [
        {
            test: /\.vue$/, // vue文件後綴
            loader: 'vue'   //使用vue-loader處理
        },
        {
            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]')
            }
        }
    ]
  },
  vue: {    // .vue 文件配置 loader 及工具 (autoprefixer)
    loaders: utils.cssLoaders({ sourceMap: useCssSourceMap }), //// 調用cssLoaders方法返回各種型的樣式對象(css: loader)
    postcss: [
      require('autoprefixer')({
        browsers: ['last 2 versions']
      })
    ]
  }
}
複製代碼

      webpack.prod.conf.js 生產環境下的配置文件

複製代碼
var path = require('path')
var config = require('../config')
var utils = require('./utils')
var webpack = require('webpack')
var merge = require('webpack-merge')// 一個能夠合併數組和對象的插件
var baseWebpackConfig = require('./webpack.base.conf')
// 用於從webpack生成的bundle中提取文本到特定文件中的插件
// 能夠抽取出css,js文件將其與webpack輸出的bundle分離
var ExtractTextPlugin = require('extract-text-webpack-plugin')  //若是咱們想用webpack打包成一個文件,css js分離開,須要這個插件
var HtmlWebpackPlugin = require('html-webpack-plugin')// 一個用於生成HTML文件並自動注入依賴文件(link/script)的webpack插件
var env = config.build.env
// 合併基礎的webpack配置
var webpackConfig = merge(baseWebpackConfig, {
    // 配置樣式文件的處理規則,使用styleLoaders
  module: {
    loaders: utils.styleLoaders({ sourceMap: config.build.productionSourceMap, extract: true })
  },
  devtool: config.build.productionSourceMap ? '#source-map' : false, // 開啓source-map,生產環境下推薦使用cheap-source-map或source-map,後者獲得的.map文件體積比較大,可是可以徹底還原之前的js代碼
  output: {
    path: config.build.assetsRoot,// 編譯輸出目錄
    filename: utils.assetsPath('js/[name].[chunkhash].js'),  // 編譯輸出文件名格式
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')  // 沒有指定輸出名的文件輸出的文件名格式
  },
  vue: { // vue裏的css也要單獨提取出來
    loaders: utils.cssLoaders({ // css加載器,調用了utils文件中的cssLoaders方法,用來返回針對各種型的樣式文件的處理方式,
      sourceMap: config.build.productionSourceMap,
      extract: true
    })
  },
  // 從新配置插件項
  plugins: [
    // http://vuejs.github.io/vue-loader/en/workflow/production.html
    // 位於開發環境下
    new webpack.DefinePlugin({
      'process.env': env
    }),
    new webpack.optimize.UglifyJsPlugin({// 醜化壓縮代碼
      compress: {
        warnings: false
      }
    }),
    new webpack.optimize.OccurenceOrderPlugin(),
    // extract css into its own file
    new ExtractTextPlugin(utils.assetsPath('css/[name].[contenthash].css')),  // 抽離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
     // filename 生成網頁的HTML名字,可使用/來控制文件文件的目錄結構,最
      // 終生成的路徑是基於webpac配置的output.path的
    new HtmlWebpackPlugin({
        // 生成html文件的名字,路徑和生產環境下的不一樣,要與修改後的publickPath相結合,不然開啓服務器後頁面空白
      filename: config.build.index,
      // 源文件,路徑相對於本文件所在的位置
      template: 'index.html',
      inject: true,
複製代碼
相關文章
相關標籤/搜索