對vue中 默認的 config/index.js:配置的詳細理解 -【以及webpack配置的理解】-config配置的目的都是爲了服務webpack的配置,給不一樣的編譯條件提供配置

當咱們須要和後臺分離部署的時候,必須配置config/index.js:javascript

用vue-cli 自動構建的目錄裏面  (環境變量及其基本變量的配置)php

var path = require('path')

module.exports = {
  build: {
    index: path.resolve(__dirname, 'dist/index.html'),
    assetsRoot: path.resolve(__dirname, 'dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    productionSourceMap: true
  },
  dev: {
    port: 8080,
    proxyTable: {}
  }
}

  

在'build'部分,咱們有如下選項:css

build.index

必須是本地文件系統上的絕對路徑。html

index.html (帶着插入的資源路徑) 會被生成。vue

若是你在後臺框架中使用此模板,你能夠編輯index.html路徑指定到你的後臺程序生成的文件。例如Rails程序,能夠是app/views/layouts/application.html.erb,或者Laravel程序,能夠是resources/views/index.blade.phpjava

build.assetsRoot

必須是本地文件系統上的絕對路徑。node

應該指向包含應用程序的全部靜態資產的根目錄。public/ 對應Rails/Laravel。webpack

build.assetsSubDirectory

被webpack編譯處理過的資源文件都會在這個build.assetsRoot目錄下,因此它不能夠混有其它可能在build.assetsRoot裏面有的文件。例如,假如build.assetsRoot參數是/path/to/distbuild.assetsSubDirectory 參數是 static, 那麼因此webpack資源會被編譯到path/to/dist/static目錄。git

每次編譯前,這個目錄會被清空,因此這個只能放編譯出來的資源文件。github

static/目錄的文件會直接被在構建過程當中,直接拷貝到這個目錄。這意味着是若是你改變這個規則,全部你依賴於static/中文件的絕對地址,都須要改變。

build.assetsPublicPath【資源的根目錄】

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

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

build.productionSourceMap

在構建生產環境版本時是否開啓source map。

dev.port

開發服務器監聽的特定端口

dev.proxyTable

定義開發服務器的代理規則。

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

 1 var path = require('path')
 2 
 3 module.exports = {
 4   build: { // production 環境
 5     env: require('./prod.env'), // 使用 config/prod.env.js 中定義的編譯環境
 6     index: path.resolve(__dirname, '../dist/index.html'), // 編譯輸入的 index.html 文件
 7     assetsRoot: path.resolve(__dirname, '../dist'), // 編譯輸出的靜態資源路徑
 8     assetsSubDirectory: 'static', // 編譯輸出的二級目錄
 9     assetsPublicPath: '/', // 編譯發佈的根目錄,可配置爲資源服務器域名或 CDN 域名
10     productionSourceMap: true, // 是否開啓 cssSourceMap
11     // Gzip off by default as many popular static hosts such as
12     // Surge or Netlify already gzip all static assets for you.
13     // Before setting to `true`, make sure to:
14     // npm install --save-dev compression-webpack-plugin
15     productionGzip: false, // 是否開啓 gzip
16     productionGzipExtensions: ['js', 'css'] // 須要使用 gzip 壓縮的文件擴展名
17   },
18   dev: { // dev 環境
19     env: require('./dev.env'), // 使用 config/dev.env.js 中定義的編譯環境
20     port: 8080, // 運行測試頁面的端口
21     assetsSubDirectory: 'static', // 編譯輸出的二級目錄
22     assetsPublicPath: '/', // 編譯發佈的根目錄,可配置爲資源服務器域名或 CDN 域名
23     proxyTable: {}, // 須要 proxyTable 代理的接口(可跨域)
24     // CSS Sourcemaps off by default because relative paths are "buggy"
25     // with this option, according to the CSS-Loader README
26     // (https://github.com/webpack/css-loader#sourcemaps)
27     // In our experience, they generally work as expected,
28     // just be aware of this issue when enabling this option.
29     cssSourceMap: false // 是否開啓 cssSourceMap
30   }
31 }

 

下面是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,// 要把<script>標籤插入到頁面哪一個標籤裏(body|true|head|false)
      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'
    }),
    // 若是文件是多入口的文件,可能存在,重複代碼,把公共代碼提取出來,又不會重複下載公共代碼了
    // (多個頁面間會共享此文件的緩存)
    // CommonsChunkPlugin的初始化經常使用參數有解析?
    // name: 這個給公共代碼的chunk惟一的標識
    // filename,如何命名打包後生產的js文件,也是能夠用上[name]、[hash]、[chunkhash]
    // minChunks,公共代碼的判斷標準:某個js模塊被多少個chunk加載了纔算是公共代碼
    // 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({ // 爲組件分配ID,經過這個插件webpack能夠分析和優先考慮使用最多的模塊,併爲它們分配最小的ID
      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
    })
  )
}

module.exports = webpackConfig

  

 vue 中build/build.js頁面

 1 // https://github.com/shelljs/shelljs
 2 require('./check-versions')() // 檢查 Node 和 npm 版本
 3 require('shelljs/global')  // 使用了 shelljs 插件,可讓咱們在 node 環境的 js 中使用 shell
 4 env.NODE_ENV = 'production'
 5 
 6 var path = require('path') 
 7 var config = require('../config') // 加載 config.js
 8 var ora = require('ora') // 一個很好看的 loading 插件
 9 var webpack = require('webpack')  // 加載 webpack
10 var webpackConfig = require('./webpack.prod.conf')  // 加載 webpack.prod.conf
11 
12 console.log( //  輸出提示信息 ~ 提示用戶請在 http 服務下查看本頁面,不然爲空白頁
13   '  Tip:\n' +
14   '  Built files are meant to be served over an HTTP server.\n' +
15   '  Opening index.html over file:// won\'t work.\n'
16 )
17 
18 var spinner = ora('building for production...')  // 使用 ora 打印出 loading + log
19 spinner.start()  // 開始 loading 動畫
20 
21 /* 拼接編譯輸出文件路徑 */
22 var assetsPath = path.join(config.build.assetsRoot, config.build.assetsSubDirectory)
23 rm('-rf', assetsPath) /* 刪除這個文件夾 (遞歸刪除) */
24 mkdir('-p', assetsPath) /* 建立此文件夾 */ 
25 cp('-R', 'static/*', assetsPath) /* 複製 static 文件夾到咱們的編譯輸出目錄 */
26 
27 webpack(webpackConfig, function (err, stats) {  //  開始 webpack 的編譯
28     // 編譯成功的回調函數
29   spinner.stop()
30   if (err) throw err
31   process.stdout.write(stats.toString({
32     colors: true,
33     modules: false,
34     children: false,
35     chunks: false,
36     chunkModules: false
37   }) + '\n')
38 })

項目入口,由package.json 文件能夠看出

"scripts": {
    "dev": "node build/dev-server.js",
    "build": "node build/build.js",
    "watch": "node build/build-watch.js"
  },

  當咱們執行 npm run dev / npm run build  / npm run watch時運行的是 node build/dev-server.js 或 node build/build.js 或node build/build-watch.js

node build/build-watch.js 是我配置的載production環境的配置基礎上在webpack的配置模塊加上 watch:true  即可實現代碼的實時編譯

相關文章
相關標籤/搜索