webpack本身有dev和prodcution两套环境,我们的项目还有uat环境,只有两套环境并无法满足项目开发的需要,因为我参考webpack搭建dev环境的方式搭建了uat环境。
首先,找到项目的package.json,找到scripts,加上uat指令的定义,
"scripts": {
"dev": "node build/dev-server.js",
"start": "node build/dev-server.js",
"uat": "node build/uat-server.js",
"build": "node build/build.js",
"lint": "eslint --ext .js,.vue src"
},
很容易理解,当我们执行npm run dev时候执行node中build目录的dev-server.js,所以我们定义了uat指令执行uat-server.js。
我拷贝了dev相关的js文件,并进行了相应的修改,修改后的js文件如下:
uat-server.js
require('./check-versions')()
var config = require('../config')
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = JSON.parse(config.uat.env.NODE_ENV)
}
var opn = require('opn')
var path = require('path')
var express = require('express')
var webpack = require('webpack')
var proxyMiddleware = require('http-proxy-middleware')
var webpackConfig = require('./webpack.uat.conf')
// default port where uat server listens for incoming traffic
var port = process.env.PORT || config.uat.port
// automatically open browser, if not set will be false
var autoOpenBrowser = !!config.uat.autoOpenBrowser
// Define HTTP proxies to your custom API backend
// https://github.com/chimurai/http-proxy-middleware
var proxyTable = config.uat.proxyTable
var app = express()
var compiler = webpack(webpackConfig)
var devMiddleware = require('webpack-dev-middleware')(compiler, {
publicPath: webpackConfig.output.publicPath,
quiet: true
})
var hotMiddleware = require('webpack-hot-middleware')(compiler, {
log: () => {},
heartbeat: 2000
})
// force page reload when html-webpack-plugin template changes
compiler.plugin('compilation', function (compilation) {
compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
hotMiddleware.publish({ action: 'reload' })
cb()
})
})
// proxy api requests
Object.keys(proxyTable).forEach(function (context) {
var options = proxyTable[context]
if (typeof options === 'string') {
options = { target: options }
}
app.use(proxyMiddleware(options.filter || context, options))
})
// handle fallback for HTML5 history API
app.use(require('connect-history-api-fallback')())
// serve webpack bundle output
app.use(devMiddleware)
// enable hot-reload and state-preserving
// compilation error display
app.use(hotMiddleware)
// serve pure static assets
var staticPath = path.posix.join(config.uat.assetsPublicPath, config.uat.assetsSubDirectory)
app.use(staticPath, express.static('./static'))
var uri = 'http://localhost:' + port
var _resolve
var readyPromise = new Promise(resolve => {
_resolve = resolve
})
console.log('> Starting uat server...')
devMiddleware.waitUntilValid(() => {
console.log('> Listening at ' + uri + '\n')
// when env is testing, don't need open it
if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') {
opn(uri)
}
_resolve()
})
var server = app.listen(port)
module.exports = {
ready: readyPromise,
close: () => {
server.close()
}
}
webpack.uat.conf.js
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
// add hot-reload related code to entry chunks
Object.keys(baseWebpackConfig.entry).forEach(function (name) {
baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
})
module.exports = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({ sourceMap: config.uat.cssSourceMap })
},
// cheap-module-eval-source-map is faster for uat
devtool: '#cheap-module-eval-source-map',
plugins: [
new webpack.DefinePlugin({
'process.env': config.uat.env
}),
// https://github.com/glenjamin/webpack-hot-middleware#installation--usage
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
}),
new FriendlyErrorsPlugin()
]
})
uat.env.js
var merge = require('webpack-merge')
var prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"uat"',
API_ROOT: '"https://uat.xxx.com"',
})
找到config下方的index.js
在dev下方增加uat的配置,配置如下:
uat: {
env: require('./uat.env'),
port: 8080,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false
}
这样,搭建了dev,uat和production三套环境,我们在dev.env.js增加API_ROOT:
var merge = require('webpack-merge')
var prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"',
API_ROOT: '"http://dev.xxx.com"',//根据项目情况配置,
})
在prod.env.js增加API_ROOT:
module.exports = {
NODE_ENV: '"production"',
API_ROOT: 'window.location.origin'
}
在配置api接口的文件中,将baseURL设置成:
axios.defaults.baseURL = process.env.API_ROOT;
这里以axios的设置为例,项目根据实际情况调整。
如此,当我们运行
npm run dev
指向的域名服务器是
API_ROOT: '"http://dev.xxx.com"',//根据项目情况配置,
当我们运行
npm run uat
指向的域名服务器是
API_ROOT: '"https://uat.xxx.com"',
这是前面配置的自定义指令,可根据项目实际情况定义自己的指令
当我们运行
npm run build
指向的域名服务器是
API_ROOT: 'window.location.origin'
打包项目的时候,打包的是根据服务器获取到相应的接口,我们就不用调来调去,也不容易出错,有问题欢迎留言讨论。