昨天项目上线,需要多个环境,折腾过程记录下。
一般来说,开发中有三个环境,开发环境、测试环境、线上环境。vue脚手架提供了两个环境,开发环境(dev)和线上环境(build)。这时候的处理方式是开发环境使用vue中的开发环境(dev),测试环境和线上环境都使用vue中的线上环境(build),但是 但是 但是,这种情况只适用于测试环境和线上环境是一模一样的时候,有些实际情况中,线上环境和测试环境不一样,比如线上的部署可能是分开部署到多个服务器,但是测试就一个服务器。这个时候,就需要再添加一个环境。
我不知道上面能不能表述清楚,反正我读起来都有点模糊。原谅我......
在打算添加一个环境的时候,没有搜索到相关的教程,看来我的面向搜索编程功力还欠火候...,然后懵懵懂懂看了npm run build
的构建过程,复制粘贴修改大法成功啦。
开始
package.json
首先修改package.json,在scripts节点中添加一个脚本指令,我添加的是testing的那个指令,刚开始我添加的test,结果里面已经存在一个了:worried:
.....
.....
"scripts": {
"dev": "node build/dev-server.js",
"start": "npm run dev",
"build": "node build/build.js",
"testing": "node build/testing.js",
"unit": "cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run",
"e2e": "node test/e2e/runner.js",
"test": "npm run unit && npm run e2e"
}
.....
.....
testing.js
在build文件夹中新建testing.js文件,配置如下
'use strict'
require('./check-versions')()
process.env.NODE_ENV = 'testing'
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.testing.conf')
const spinner = ora('building for testing...')
spinner.start()
rm(path.join(config.testing.assetsRoot, config.testing.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
}) + '\n\n')
if (stats.hasErrors()) {
console.log(chalk.red(' testing failed with errors.\n'))
process.exit(1)
}
console.log(chalk.cyan(' testing 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'
))
})
})
webpack.testing.conf.js
在build文件中,新建webpack.testing.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 env = config.testing.env
const webpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.testing.testingSourceMap,
extract: true
})
},
devtool: config.testing.testingSourceMap ? '#source-map' : false,
output: {
path: config.testing.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
}),
// UglifyJs do not support ES6+, you can also use babel-minify for better treeshaking: https://github.com/babel/minify
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
sourceMap: true
}),
// extract css into its own file
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css')
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
new OptimizeCSSPlugin({
cssProcessorOptions: {
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.testing.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 vender modules does not change
new webpack.HashedModuleIdsPlugin(),
// split vendor js into its own file
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: function (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',
chunks: ['vendor']
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.testing.assetsSubDirectory,
ignore: ['.*']
}
])
]
})
if (config.testing.testingGzip) {
const CompressionWebpackPlugin = require('compression-webpack-plugin')
webpackConfig.plugins.push(
new CompressionWebpackPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(
'\\.(' +
config.testing.testingGzipExtensions.join('|') +
')$'
),
threshold: 10240,
minRatio: 0.8
})
)
}
if (config.testing.bundleAnalyzerReport) {
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig
utils.js
在build文件夹中,修改utils.js文件,修改有两处,修改如下:
.....
.....
exports.assetsPath = function (_path) {
let assetsSubDirectory = ''
if (process.env.NODE_ENV === 'production') {
assetsSubDirectory = config.build.assetsSubDirectory
} else if (process.env.NODE_ENV === 'testing') {
assetsSubDirectory = config.testing.assetsSubDirectory
} else {
assetsSubDirectory = config.dev.assetsSubDirectory
}
return path.posix.join(assetsSubDirectory, _path)
}
exports.cssLoaders = function (options) {
options = options || {}
const cssLoader = {
loader: 'css-loader',
options: {
minimize: process.env.NODE_ENV === ('production'||'testing'),
sourceMap: options.sourceMap
}
}
....
....
webpack.base.conf.js
在build文件夹中修改webpack.base.conf.js,修改就是添加了一个getPath方法和使用这个方法,修改如下:
....
....
function getPath(env) {
if (env === "production") {
return config.build.assetsPublicPath
} else if (env === "testing") {
return config.testing.assetsPublicPath
} else {
return config.dev.assetsPublicPath
}
}
module.exports = {
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: getPath(process.env.NODE_ENV)
},
......
.....
vue-loader.conf.js
在build文件夹中修改vue-loader.conf.js,修改就是添加了一个getSourchMap方法和使用这个方法,还有一个这个extract也要改下,修改如下:
....
....
function getSourchMap(env) {
if (env === "production") {
return config.build.productionSourceMap
} else if (env === "testing") {
return config.testing.testingSourceMap
} else {
return config.dev.cssSourceMap
}
}
module.exports = {
loaders: utils.cssLoaders({
sourceMap: getSourchMap(process.env.NODE_ENV),
extract: process.env.NODE_ENV === ('production'||'testing')
}),
transformToRequire: {
video: 'src',
source: 'src',
img: 'src',
image: 'xlink:href'
}
}
....
....
testing.env.js
在config文件中,新建testing.env.js文件,配置如下:
'use strict'
module.exports = {
NODE_ENV: '"testing"',
.....
.....
}
index.js
在config文件中,修改index.js文件,添加testing节点,修改如下:
....
.....
testing: {
env: require('./testing.env'),
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: '',
assetsPublicPath: '/',
testingSourceMap: true,
// 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
testingGzip: false,
testingGzipExtensions: ['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
}
....
....
以上就是需要修改的内容,执行以下命令即可查看打包结果
npm run testing
不出意外,会生成一个dist的目录
以上就是本文的所有内容,感觉还是有些麻烦,如果有更好的方法,欢迎交流。