
昨天項目上線,需要多個環(huán)境,折騰過程記錄下。
一般來說,開發(fā)中有三個環(huán)境,開發(fā)環(huán)境、測試環(huán)境、線上環(huán)境。vue腳手架提供了兩個環(huán)境,開發(fā)環(huán)境(dev)和線上環(huán)境(build)。這時候的處理方式是開發(fā)環(huán)境使用vue中的開發(fā)環(huán)境(dev),測試環(huán)境和線上環(huán)境都使用vue中的線上環(huán)境(build),但是 但是 但是,這種情況只適用于測試環(huán)境和線上環(huán)境是一模一樣的時候,有些實際情況中,線上環(huán)境和測試環(huán)境不一樣,比如線上的部署可能是分開部署到多個服務器,但是測試就一個服務器。這個時候,就需要再添加一個環(huán)境。
我不知道上面能不能表述清楚,反正我讀起來都有點模糊。原諒我......
在打算添加一個環(huán)境的時候,沒有搜索到相關(guān)的教程,看來我的面向搜索編程功力還欠火候...,然后懵懵懂懂看了npm run build的構(gòu)建過程,復制粘貼修改大法成功啦。
開始
package.json
首先修改package.json,在scripts節(jié)點中添加一個腳本指令,我添加的是testing的那個指令,剛開始我添加的test,結(jié)果里面已經(jīng)存在一個了: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節(jié)點,修改如下:
....
.....
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
}
....
....
以上就是需要修改的內(nèi)容,執(zhí)行以下命令即可查看打包結(jié)果
npm run testing
不出意外,會生成一個dist的目錄
以上就是本文的所有內(nèi)容,感覺還是有些麻煩,如果有更好的方法,歡迎交流。