Vue-cliコマンドラインツール分析


Vue.jsは公式コマンドラインツールを提供しています。大規模な単一ページアプリケーションを構築するために迅速に利用できます。vue-webpack-boilerplateは、公式定義は:
full-feature d Webpack setup with hot-reload,lint-on-save,unit testing&css extraction.
ディレクトリ構造:

├── README.md
├── build
│  ├── build.js
│  ├── utils.js
│  ├── vue-loader.conf.js
│  ├── webpack.base.conf.js 
│  ├── webpack.dev.conf.js
│  └── webpack.prod.conf.js
├── config
│  ├── dev.env.js
│  ├── index.js
│  └── prod.env.js
├── index.html
├── package.json
├── src
│  ├── App.vue
│  ├── assets
│  │  └── logo.png
│  ├── components
│  │  └── Hello.vue
│  └── main.js
└── static
config環境配置
configプロファイルはdevServerの関連設定を設定するために使用され、NODE_を配置することによりENVはどのようなモード(開発、生産、テストまたはその他)を使うかを決定します。

config
|- index.js #    
|- dev.env.js #    
|- prod.env.js #    
index.js

'use strict'
const path = require('path');

module.exports = {
 dev: {

  //   
  assetsSubDirectory: 'static', // path:              
  assetsPublicPath: '/', // publicPath:           
  proxyTable: {}, //     : proxy: [{context: ["/auth", "/api"],target: "http://localhost:3000",}]

  //          
  host: 'localhost',
  port: 8080,
  autoOpenBrowser: true, //        devServer.open
  errorOverlay: true, //         devServer.overlay
  notifyOnErrors: true, //    friendly-errors-webpack-plugin
  poll: true, //       (file system)         devServer.watchOptions

  // source map
  cssSourceMap: false, // develop      sourceMap
  devtool: 'eval-source-map' //            :eval, eval-source-map(  ), cheap-eval-source-map, cheap-module-eval-source-map   :https://doc.webpack-china.org/configuration/devtool
 },
 build: {
  // index    
  index: path.resolve(__dirname, '../dist/index.html'),

  //   
  assetsRoot: path.resolve(__dirname, '../dist'),
  assetsSubDirectory: 'static',
  assetsPublicPath: '/',

  // bundleAnalyzerReport
  bundleAnalyzerReport: process.env.npm_config_report,

  // Gzip
  productionGzip: false, //    false
  productionGzipExtensions: ['js', 'css'],

  // source map
  productionSourceMap: true, // production      sourceMap
  devtool: '#source-map' // devtool: 'source-map' ?
 }
}

dev.env.js

'use strict'
const merge = require('webpack-merge');
const prodEnv = require('./prod.env');

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"'
});
prod.env.js
'use strict'
module.exports = {
  NODE_ENV: '"production"'
};

build Webpack配置

build
|- utils.js #   
|- webpack.base.conf.js #      
|- webpack.dev.conf.js #        
|- webpack.prod.conf.js #        
|- build.js #    
実用コードセグメントutils.js

const config = require('../config')
const path = require('path')

exports.assetsPath = function (_path) {
  const assetsSubDirectory = process.env.NODE_ENV === 'production'
    ? config.build.assetsSubDirectory // 'static'
    : config.dev.assetsSubDirectory
  return path.posix.join(assetsSubDirectory, _path) // posix      
}

exports.cssLoaders = function (options) { //   : ({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
 options = options || {};

 // cssLoader
 const cssLoader = {
  loader: 'css-loader',
  options: { sourceMap: options.sourceMap }
 }
 // postcssLoader
 var postcssLoader = {
  loader: 'postcss-loader',
  options: { sourceMap: options.sourceMap }
 }

 //    loader
 function generateLoaders (loader, loaderOptions) {
  const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader] //     loader
  if (loader) {
   loaders.push({
    loader: loader + '-loader',
    options: Object.assign({}, loaderOptions, { //    options   
     sourceMap: options.sourceMap
    })
   })
  }

  //        css
  if (options.extract) { //    options    extract   true       
   return ExtractTextPlugin.extract({
    use: loaders,
    fallback: 'vue-style-loader' //      vue-style-loader
   })
  } else {
   return ['vue-style-loader'].concat(loaders)
  }
 }

 return { //      loaders   
  css: generateLoaders(),
  postcss: generateLoaders(),
  less: generateLoaders('less'), 
  //   :[
  // { loader: 'css-loader', options: { sourceMap: true/false } },
  // { loader: 'postcss-loader', options: { sourceMap: true/false } },
  // { loader: 'less-loader', options: { sourceMap: true/false } },
  // ]
  sass: generateLoaders('sass', { indentedSyntax: true }),
  scss: generateLoaders('sass'),
  stylus: generateLoaders('stylus'),
  styl: generateLoaders('stylus')
 }
}

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
  })
  //   :
  // {
  //  test: new RegExp(\\.less$),
  //  use: {
  //   loader: 'less-loader', options: { sourceMap: true/false }
  //  }
  // }
 }
 return output
}

exports.createNotifierCallback = function () { //    friendly-errors-webpack-plugin
 //     :notifier.notify('message');
 const notifier = require('node-notifier'); //          

 return (severity, errors) => {
  //           error       notifier     
  if (severity !== 'error') { return } //         'error'   'warning'
  const error = errors[0]

  const filename = error.file && error.file.split('!').pop();
  notifier.notify({
   title: pkg.name,
   message: severity + ': ' + error.name,
   subtitle: filename || ''
   // icon: path.join(__dirname, 'logo.png') //     
  })
 }
}

基礎配置ファイルwebpack.base.com nf.js
ベースのwebpackプロファイルは主にモードによって輸入口を定義しています。また、vue、babelなどの各種モジュールを処理するのが基本です。他のモードのプロファイルはこれをベースにwebpack-mergeで統合されます。

'use strict'
const path = require('path');
const utils = require('./utils');
const config = require('../config');

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

module.exports = {
 context: path.resolve(__dirname, '../'), //     
 entry: {
  app: './src/main.js'
 },
 output: {
  path: config.build.assetsRoot, //   '../dist'
  filename: '[name].js',
  publicPath: process.env.NODE_ENV === 'production'
  ? config.build.assetsPublicPath //     publicpath
  : config.dev.assetsPublicPath //     publicpath
 },
 resolve: { //         ,      
  extensions: ['.js', '.vue', '.json'], 
  alias: {  //     
   'vue$': 'vue/dist/vue.esm.js', 
   '@': resolve('src') //   '@/components/HelloWorld'
  }
 },
 module: {
  rules: [{
    test: /\.vue$/, // vue   babel  
    loader: 'vue-loader',
    options: vueLoaderConfig //   : vue-loader     
   },{
    test: /\.js$/, // babel
    loader: 'babel-loader',
    include: [resolve('src')]
   },{ // url-loader             ,    DataURL, base64
    test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, // url-loader   
    loader: 'url-loader',
    options: { //         query  options
     limit: 10000, //      
     name: utils.assetsPath('img/[name].[hash:7].[ext]') // hash:7    7     hash
    }
   },{
    test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/, // url-loader    
    loader: 'url-loader',
    options: {
     limit: 10000,
     name: utils.assetsPath('media/[name].[hash:7].[ext]')
    }
   },{
    test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, // url-loader   
    loader: 'url-loader',
    options: {
     limit: 10000,
     name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
    }
   }
  ]
 },
 node: { //    polyfill   mock
  setImmediate: false,
  dgram: 'empty',
  fs: 'empty',
  net: 'empty',
  tls: 'empty',
  child_process: 'empty'
 }
}

開発モード設定ファイルwebpack.dev.com nf.js
開発モードのプロファイルは主にconfigのdevServerに対する設定を引用し、cssファイルの処理に対してDefinePluginを用いて生産環境やその他のプラグインを判断する。

'use strict'
const webpack = require('webpack');
const config = require('../config');
const merge = require('webpack-merge');
const baseWebpackConfig = require('./webpack.base.conf');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const portfinder = require('portfinder'); //            
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin'); //         

const devWebpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
    //       css, postcss, less    ,          ,      css   postcss   
  },

  devtool: config.dev.devtool,//      (meta info)    

  // devServer   /config/index.js    
  devServer: {
    clientLogLevel: 'warning', // console         ,      none, error, warning    info
    historyApiFallback: true, // History API     404          index.html
    hot: true, //      
    compress: true, // gzip
    host: process.env.HOST || config.dev.host, // process.env   
    port: process.env.PORT || config.dev.port, // process.env   
    open: config.dev.autoOpenBrowser, //          
    overlay: config.dev.errorOverlay ? { // warning   error     
      warnings: true,
      errors: true,
    } : false,
    publicPath: config.dev.assetsPublicPath, //   publicPath
    proxy: config.dev.proxyTable, //   
    quiet: true, //                    FriendlyErrorsPlugin     true
    watchOptions: {
      poll: config.dev.poll, //         
    }
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': require('../config/dev.env') //            
    }),
    new webpack.HotModuleReplacementPlugin(), //    
    new webpack.NamedModulesPlugin(), //               ,   id
    new webpack.NoEmitOnErrorsPlugin(), //                ,                 
    new HtmlWebpackPlugin({ //            html5                     
      filename: 'index.html',
      template: 'index.html',
      inject: true //        true, 'head', 'body', false
    }),
  ]
})

module.exports = new Promise((resolve, reject) => {
 portfinder.basePort = process.env.PORT || config.dev.port; //          
 portfinder.getPort((err, port) => {
  if (err) { reject(err) } else {
   process.env.PORT = port; // process     
   devWebpackConfig.devServer.port = port; //    devServer   

   devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({ //       
    compilationSuccessInfo: {
     messages: [`Your application is running here: http://${config.dev.host}:${port}`],
    },
    onErrors: config.dev.notifyOnErrors ? utils.createNotifierCallback() : undefined
   }))

   resolve(devWebpackConfig);
  }
 })
})

生産モード設定ファイルwebpack.prod.com nf.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 env = process.env.NODE_ENV === 'production'
 ? require('../config/prod.env')
 : require('../config/dev.env')

const webpackConfig = merge(baseWebpackConfig, {
 module: {
  rules: utils.styleLoaders({
   sourceMap: config.build.productionSourceMap, // production     sourceMap
   extract: true, // util   styleLoaders      generateLoaders   
   usePostCSS: true
  })
 },
 devtool: config.build.productionSourceMap ? config.build.devtool : false,
 output: {
  path: config.build.assetsRoot,
  filename: utils.assetsPath('js/[name].[chunkhash].js'),
  chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
 },
 plugins: [
  new webpack.DefinePlugin({ 'process.env': env }),
  new webpack.optimize.UglifyJsPlugin({ // js          include, cache  ,    babel-minify
   compress: { warnings: false },
   sourceMap: config.build.productionSourceMap,
   parallel: true //       cpu
  }),
  //    js      css
  new ExtractTextPlugin({
   filename: utils.assetsPath('css/[name].[contenthash].css'),
   allChunks: false,
  }),
  //       css
  new OptimizeCSSPlugin({
   cssProcessorOptions: config.build.productionSourceMap
   ? { safe: true, map: { inline: false } }
   : { safe: true }
  }),
  //    html
  new HtmlWebpackPlugin({
   filename: process.env.NODE_ENV === 'production'
    ? config.build.index
    : 'index.html',
   template: 'index.html',
   inject: true,
   minify: {
    removeComments: true,
    collapseWhitespace: true,
    removeAttributeQuotes: true
   },
   chunksSortMode: 'dependency' //   dependency      
  }),
  new webpack.HashedModuleIdsPlugin(), //                   hash      id
  new webpack.optimize.ModuleConcatenationPlugin(), //              
  //       
  new webpack.optimize.CommonsChunkPlugin({
   name: 'vendor',
   minChunks: function (module) {
    return (
     module.resource &&
     /\.js$/.test(module.resource) &&
     module.resource.indexOf(
      path.join(__dirname, '../node_modules')
     ) === 0
    )
   }
  }),
  new webpack.optimize.CommonsChunkPlugin({
   name: 'manifest',
   minChunks: Infinity
  }),
  new webpack.optimize.CommonsChunkPlugin({
   name: 'app',
   async: 'vendor-async',
   children: true,
   minChunks: 3
  }),

  //       
  new CopyWebpackPlugin([{
    from: path.resolve(__dirname, '../static'),
    to: config.build.assetsSubDirectory,
    ignore: ['.*']
  }])]
})

if (config.build.productionGzip) { // gzip   
 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, // 10kb           
   minRatio: 0.8 //        .8     
  })
 )
}

if (config.build.bundleAnalyzerReport) { //          
 const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
 webpackConfig.plugins.push(new BundleAnalyzerPlugin());
}

module.exports = webpackConfig;

build.jsコンパイル入口

'use strict'

process.env.NODE_ENV = 'production'; //            
const ora = require('ora'); //loading...   
const rm = require('rimraf'); //     'rm -rf'
const chalk = require('chalk'); //stdout    
const webpack = require('webpack');
const path = require('path');
const config = require('../config');
const webpackConfig = require('./webpack.prod.conf');

const spinner = ora('    ...');
spinner.start();

//      
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
  if (err) throw err;
  //              
  webpack(webpackConfig, function (err, stats) {
    spinner.stop();
    if (err) throw err;
  
  //     ,      
    process.stdout.write(stats.toString({
      colors: true,
      modules: false,
      children: false,
      chunks: false,
      chunkModules: false
    }) + '

'); //error if (stats.hasErrors()) { console.log(chalk.red(' .
')); process.exit(1); } // console.log(chalk.cyan(' .
')) console.log(chalk.yellow( ' file:// , http(s)://.
' )) }) })
以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。