vueファミリーバケツ(二)vue-cliテスト環境の増加

9308 ワード

1.テスト環境の構成testBuildを追加
config/indexを変更します.jsファイル、testBuildオブジェクトを作成します.内容はbuildオブジェクトと基本的に同じですが、パッケージされたフォルダをdist-testに変更します.
 testBuild: {
    // Template for index.html
    index: path.resolve(__dirname, '../dist-test/index.html'),

    // Paths
    assetsRoot: path.resolve(__dirname, '../dist-test'),
    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,
    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
  }

2.testを追加する.dev.jsファイル
'use strict'
module.exports = {
  NODE_ENV: '"test"',
  API_ROOT:'"         "'
}


3.testを追加する.jsファイル
buildファイルの下にtestを作成します.jsファイル、コンテンツ、および同ディレクトリのbuild.jsはほぼ一致していますが、いくつかのパラメータを変更する必要があります.
1.環境がtestになる
process.env.NODE_ENV = 'test'

2.導入ファイルがwebpackになる.test.conf.js
const webpackConfig = require('./webpack.test.conf')

3.buildオブジェクトをテストオブジェクトtestBuildに変更
'use strict'
require('./check-versions')()

process.env.NODE_ENV = 'test'

const ora = require('ora')
const rm = require('rimraf')
const path = require('path')
const chalk = require('chalk')
const webpack = require('webpack')
const config = require('../config')
const webpackConfig = require('./webpack.test.conf')

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

rm(path.join(config.testBuild.assetsRoot, config.testBuild.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
      }) + '

') if (stats.hasErrors()) { console.log(chalk.red(' Build failed with errors.
')) process.exit(1) } console.log(chalk.cyan(' Build complete.
')) console.log(chalk.yellow( ' Tip: built files are meant to be served over an HTTP server.
' + ' Opening index.html over file:// won\'t work.
' )) }) })

4.webpackを追加する.test.conf.js
buildフォルダの下にwebpackを追加します.test.conf.js、コンテンツと同ディレクトリの下webpack.prod.conf.jsはほぼ一致しており、修正するだけです.
1.導入ファイルをconfig/testに変更する.env.js
const env = require('../config/test.env')

2.buildオブジェクトをテストオブジェクトtestBuildに変更
'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 env = require('../config/test.env')

const webpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({
      sourceMap: config.testBuild.productionSourceMap,
      extract: true,
      usePostCSS: true
    })
  },
  devtool: config.testBuild.productionSourceMap ? config.testBuild.devtool : false,
  output: {
    path: config.testBuild.assetsRoot,
    filename: utils.assetsPath('js/[name].[chunkhash].js'),
    chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
  },
  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.testBuild.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'
    }),
    // 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.testBuild.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})

if (config.testBuild.productionGzip) {
  const CompressionWebpackPlugin = require('compression-webpack-plugin')

  webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp(
        '\\.(' +
        config.testBuild.productionGzipExtensions.join('|') +
        ')$'
      ),
      threshold: 10240,
      minRatio: 0.8
    })
  )
}

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

module.exports = webpackConfig


5.package.jsonにtestコマンドを追加
packageでjsonにコマンドラインスクリプトtestコマンドを追加し、buildフォルダの下のtestを指します.js
"scripts": {
    "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
    "start": "npm run dev",
    "build": "node build/build.js",
    "test": "node build/test.js"
  }

次にnpm run testを実行するとテストパッケージが打てます
6.後ろに書く
今は環境が整っているので、次はaxios--HTTPライブラリを導入して、リクエストを始めましょう.