Vue項目2、vue-cli2.x腳手架搭建build文件夾及config文件夾詳解

build文件夾下
build.js
'use strict'                                    // js的嚴格模式
require('./check-versions')()                   // node和npm的版本檢查

process.env.NODE_ENV = 'production'             // 設置環境變量爲生產環境

// 導進各模塊
const ora = require('ora')                      // loading模塊
const rm = require('rimraf')
const path = require('path')
const chalk = require('chalk')
const webpack = require('webpack')
const config = require('../config')
const webpackConfig = require('./webpack.prod.conf')

const spinner = ora('building for production...')
spinner.start()

/*
    rm方法刪除dist/static文件夾
        若刪除中有錯誤則拋出異常並終止程序
        若沒有錯誤則繼續執行,構建webpack
            結束動畫
            如有異常則拋出
            標準輸出流,相似於console.log
*/
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
  if (err) throw err
  webpack(webpackConfig, (err, stats) => {
    spinner.stop()
    if (err) throw err
    process.stdout.write(stats.toString({
      colors: true,                     // 增長控制檯顏色開關
      modules: false,                   // 是否增長內置模塊信息
      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\n')                        // 編譯過程持續打印
    // 編譯出錯的信息
    if (stats.hasErrors()) {
      console.log(chalk.red('  Build failed with errors.\n'))
      process.exit(1)
    }
    // 編譯成功的信息
    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'
    ))
  })
})

 

 

check-versions.js ==》node和npm的版本檢查
'use strict'                                            // js的嚴格模式

// 導進各模塊
const chalk = require('chalk')
const semver = require('semver')
const packageConfig = require('../package.json')
const shell = require('shelljs')                        // shell.js插件,執行unix系統命令

function exec (cmd) {
  // 腳本能夠經過child_process模塊新建子進程,從而執行Unix系統命令
  // 將cmd參數傳遞的值轉換成先後沒有空格的字符串,也就是版本號
  return require('child_process').execSync(cmd).toString().trim()
}

//聲明常量數組,數組內容爲有關node相關信息的對象
const versionRequirements = [
  {
    name: 'node',                                       //對象名稱爲node
    currentVersion: semver.clean(process.version),      //使用semver插件,把版本信息轉換成規定格式
    versionRequirement: packageConfig.engines.node      //規定package.json中engines選項的node版本信息
  }
]

if (shell.which('npm')) {                               //which爲linux指令,在$path規定的路徑下查找符合條件的文件
  versionRequirements.push({
    name: 'npm',
    currentVersion: exec('npm --version'),              //調用npm --version命令,而且把參數返回給exec函數獲取純淨版本
    versionRequirement: packageConfig.engines.npm       //規定package.json中engines選項的node版本信息
  })
}

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

  for (let i = 0; i < versionRequirements.length; i++) {
    const mod = versionRequirements[i]
    // 若是版本號不符合package.json文件中指定的版本號,就執行warning.push...
    // 當前版本號用紅色標識,要求版本號用綠色標識
    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 (let i = 0; i < warnings.length; i++) {
      const warning = warnings[i]
      console.log('  ' + warning)
    }

    console.log()
    process.exit(1)
  }
}

 

 

utils.js
'use strict'
const path = require('path')
const config = require('../config')                                 // 引入config下的index.js文件
const ExtractTextPlugin = require('extract-text-webpack-plugin')    // 一個插件,抽離css樣式,防止將樣式打包在js中引發樣式加載錯亂
const packageConfig = require('../package.json')
// 導出assetsPath
exports.assetsPath = function (_path) {
  const assetsSubDirectory = process.env.NODE_ENV === 'production'
    ? config.build.assetsSubDirectory
    : config.dev.assetsSubDirectory

  return path.posix.join(assetsSubDirectory, _path)                 // path.join返回絕對路徑(在電腦上的實際位置);path.posix.join返回相對路徑
}

exports.cssLoaders = function (options) {
  options = options || {}

  const cssLoader = {
    loader: 'css-loader',
    options: {
      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) {
    const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader]

    if (loader) {
      loaders.push({
        loader: loader + '-loader',
        options: Object.assign({}, loaderOptions, {
          sourceMap: options.sourceMap
        })
      })
    }

    // Extract CSS when that option is specified
    // (which is the case during production build)
    if (options.extract) {
      return ExtractTextPlugin.extract({
        use: loaders,
        fallback: 'vue-style-loader'
      })
    } else {
      return ['vue-style-loader'].concat(loaders)
    }
  }

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

// Generate loaders for standalone style files (outside of .vue)
exports.styleLoaders = function (options) {
  const output = []
  const loaders = exports.cssLoaders(options)

  for (const extension in loaders) {
    const loader = loaders[extension]
    output.push({
      test: new RegExp('\\.' + extension + '$'),
      use: loader
    })
  }

  return output
}

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')
    })
  }
}

 

 

vue-loader.conf.js
'use strict'
const utils = require('./utils')
const config = require('../config')
const isProduction = process.env.NODE_ENV === 'production'  // 是否爲生產環境
const sourceMapEnabled = isProduction
  ? config.build.productionSourceMap
  : config.dev.cssSourceMap

module.exports = {
  loaders: utils.cssLoaders({                                // 載入utils中的cssloaders返回配置好的css-loader和vue-style=loader
    sourceMap: sourceMapEnabled,
    extract: isProduction
  }),
  cssSourceMap: sourceMapEnabled,                            // 是否開啓css資源map
  cacheBusting: config.dev.cacheBusting,                     // 是否開啓cacheBusting
  transformToRequire: {
    video: ['src', 'poster'],
    source: 'src',
    img: 'src',
    image: 'xlink:href'
  }
}

 

 

webpack.base.conf.js
'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')

function resolve (dir) {
  return path.join(__dirname, '..', dir)
}



module.exports = {
  context: path.resolve(__dirname, '../'),
  // 輸入
  entry: {
    app: './src/main.js'
  },
  // 輸出
  output: {
    path: config.build.assetsRoot,                      // 打包後文件輸出路徑,config/index.js中build.assetsRoot
    filename: '[name].js',                              // 輸出文件名稱默認使用原名
    publicPath: process.env.NODE_ENV === 'production'   // 文件引用路徑
      ? config.build.assetsPublicPath
      : config.dev.assetsPublicPath
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'],               // 省略擴展名,也就是說當使用.js .vue .json文件導入能夠省略後綴名
    alias: {
      'vue$': 'vue/dist/vue.esm.js',                    // $符號指精確匹配,路徑和文件名要詳細
      '@': resolve('src'),                              // resolve('src') 指的是項目根目錄中的src文件夾目錄,使用@符號代替
    }
  },
  // 用於解析不一樣的模塊
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',      // 解析.vue文件
        options: vueLoaderConfig
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',     // 對js文件使用babel-loader轉碼,用於解析es6等代碼
        include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]   // 指明那些文件夾下的js文件須要使用該loader
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',       // 使用url-loader插件,將圖片轉爲base64格式字符串
        options: {
          limit: 10000,             // 10000個字節如下的文件才用來轉爲dataUrl
          name: utils.assetsPath('img/[name].[hash:7].[ext]')   //超過10000字節的圖片,就按照制定規則設置生成的圖片名稱,能夠看到用了7位hash碼來標記,.ext文件是一種索引式文件系統
        }
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          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: {
    // 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'
  }
}

 

 

webpack.dev.conf.js
'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const path = require('path')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin') // 一個用於生成HTML文件並自動注入依賴文件(link/script)的webpack插件
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')// 用於更友好地輸出webpack的警告、錯誤等信息
// 獲取port
const portfinder = require('portfinder')

const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)

/*
    合併基礎的webpack配置
        第一個參數baseWebpackConfig,是webpack基本配置文件webpack.base.conf.js中的配置
*/
const devWebpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true }) // 配置樣式文件的處理規則,使用styleLoaders
  },
  // 配置Source Maps。在開發中使用cheap-module-eval-source-map更快
  devtool: config.dev.devtool, 

  // these devServer options should be customized in /config/index.js
  devServer: {
    clientLogLevel: 'warning',
    historyApiFallback: {
      rewrites: [
        { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
      ],
    },
    hot: true,          // 是否啓用webpack的模塊熱替換特性。主要是用於開發過程當中
    contentBase: false, // since we use CopyWebpackPlugin.
    compress: true,     // 一切服務是否都啓用gzip壓縮
    host: HOST || config.dev.host,          // 指定一個host,默認是localhost。若是有全局host就用全局,不然就用index.js中的設置。
    port: PORT || config.dev.port,          // 指定端口
    open: config.dev.autoOpenBrowser,       // 是否在瀏覽器開啓本dev server
    overlay: config.dev.errorOverlay        // 當有編譯器錯誤時,是否在瀏覽器中顯示全屏覆蓋。
      ? { warnings: false, errors: true }
      : false,
    publicPath: config.dev.assetsPublicPath,
    proxy: config.dev.proxyTable,          // 代理:若是你有單獨的後端開發服務器api,而且但願在同域名下發送api請求,那麼代理某些URL會頗有用。
    quiet: true, // necessary for FriendlyErrorsPlugin
    watchOptions: {
      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({
      filename: 'index.html',
      template: 'index.html',
      inject: true
    }),
    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.dev.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})

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: {
          messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
        },
        onErrors: config.dev.notifyOnErrors
        ? utils.createNotifierCallback()
        : undefined
      }))

      resolve(devWebpackConfig)
    }
  })
})

 

 

webpack.prod.conf.js

 

'use strict'
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const PrerenderSPAPlugin = require('prerender-spa-plugin')

const env = require('../config/prod.env')

// 合併基礎的webpack配置
const webpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({
      sourceMap: config.build.productionSourceMap,
      extract: true,
      usePostCSS: true
    })
  },
  devtool: config.build.productionSourceMap ? config.build.devtool : 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 UglifyJsPlugin({
      uglifyOptions: {
        compress: {
          warnings: false
        }
      },
      sourceMap: config.build.productionSourceMap,
      parallel: true
    }),
    // extract css into its own file
    new ExtractTextPlugin({
      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({
      cssProcessorOptions: config.build.productionSourceMap
        ? { safe: true, map: { inline: false } }
        : { safe: true }
    }),
    // 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: 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'
    }),
    new PrerenderSPAPlugin({
      staticDir: path.join(__dirname, 'dist'),
      routes: [ '/', '/moviesDetail'],
      renderer: new Renderer({
        inject: {
          foo: 'bar'
        },
        headless: false,
        renderAfterDocumentEvent: 'render-event'
      })
    }),
    // 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({
      name: 'vendor',
      minChunks (module) {
        // 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',
      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
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.build.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})

if (config.build.productionGzip) {
  const 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) {
  const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
  webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}

module.exports = webpackConfig

 

 

 

config文件夾下css

 

index.js
'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.

// 用於處理路徑統一的問題
const path = require('path')

module.exports = {
  // 開發環境的配置
  dev: {
    // Paths
    assetsSubDirectory: 'static',                   // 靜態資源文件夾
    assetsPublicPath: '/',                          // 發佈路徑
    // 通常解決跨域請求api
    proxyTable: {
        '/api': {
            target: 'http://api.douban.com/v2',     // 目標url
            changeOrigin: true,                     // 是否跨域
            pathRewrite: {
                '^/api': ''                         // 可使用 /api 等價於 http://api.douban.com/v2
            }
        }
    },

    // Various Dev Server settings
    host: 'localhost', // can be overwritten by process.env.HOST
    port: 8080,                 // dev-server的端口號,能夠自行更改
    autoOpenBrowser: false,     // 是否自定代開瀏覽器
    errorOverlay: true,         // 查詢錯誤
    notifyOnErrors: true,       // 通知錯誤
    poll: false,                // poll輪詢,webpack爲咱們提供devserver是能夠監控文件改動的,有些狀況下卻不能工做,能夠設置一個輪詢解決

    
    /**
     * Source Maps
     */

    // https://webpack.js.org/configuration/devtool/#development
    devtool: 'cheap-module-eval-source-map',        // webpack用於方便調試的配置

    // 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,       // devtool的配置當文件名插入新的hash致使清除緩存時是否生成source maps,默認爲true

    cssSourceMap: true        // 是否開啓cssSourceMap
  },
  // 生產編譯環境下的一些配置
  build: {
    // 下面是相對路徑的拼接
    index: path.resolve(__dirname, '../dist/index.html'),

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

    /**
     * Source Maps
     */

    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,                      // 是否在生產環境中壓縮代碼,若是要壓縮必須安裝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
    bundleAnalyzerReport: process.env.npm_config_report     // 是否開啓打包後的分析報告
  }
}

 

dev.env.js
'use strict'
// 該插件是用來合併對象,也就是配置文件用的
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')

// 將兩個配置對象合併導出,NODE_ENV是一個環境變量,指定development環境
module.exports = merge(prodEnv, {
  NODE_ENV: '"development"'
})

 

prod.env.js
// 導出一個對象,NODE_ENV是一個環境變量,指定production環境
'use strict'
module.exports = {
  NODE_ENV: '"production"'
}
相關文章
相關標籤/搜索