vue分环境打包配置不同命令
1、安装cross-env (cross-env能跨平台地设置及使用环境变量)cnpm/npm i cross-env -D
2、新建模板 红色的为相关文件
3、配置各个文件
(1)config下面的index.js
'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation. const path = require('path') module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': {
target: 'http://xxxxx', //需要代理的后台地址 解决跨域设置
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
},
// Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST
port: 9999, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: true,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions- // Use Eslint Loader?
// If true, your code will be linted during bundling and
// linting errors and warnings will be shown in the console.
useEslint: false,
// If true, eslint errors and warnings will also be shown in the error overlay
// in the browser.
showEslintErrorsInOverlay: false, /**
* Source Maps
*/ // https://webpack.js.org/configuration/devtool/#development
devtool: 'cheap-module-eval-source-map', // If you have problems debugging vue-files in devtools,
// set this to false - it *may* help
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true, cssSourceMap: true
}, build: {
prodEnv: require('./prod.env'), //新增
testEnv: require('./test.env'),//新增
devEnv: require('./dev.env'), //新增
// Template for index.html
index: path.resolve(__dirname, '../dist/index.html'), // Paths
assetsRoot: path.resolve(__dirname, '../dist'),
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)config下面的 dev.evn.js
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env') module.exports = merge(prodEnv, {
NODE_ENV: '"development"',
ENV_CONFIG: '"dev"', // 新增
BASE_URL: '"api"', // 新增 DEV
})
(3)config下面的 test.evn.js
'use strict'
const merge = require('webpack-merge')
const devEnv = require('./dev.env') module.exports = merge(devEnv, {
NODE_ENV: '"testing"',
ENV_CONFIG: '"test"', //新增
BASE_URL: '"http://www.test.com"', // test测试地址
})
(4)config下面的 prod.evn.js
'use strict'
module.exports = {
NODE_ENV: '"production"',
ENV_CONFIG: '"prod"', // 新增
BASE_URL: '"http://www.produciton.com"', // prod
}
(5)build下面的 build.js
'use strict'
require('./check-versions')() // process.env.NODE_ENV = 'production' // 原本的注释掉 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.prod.conf') // const spinner = ora('building for production...') // 原本的注释掉
const spinner = ora('building for' + process.env.NODE_ENV + 'of' + process.env.env_config + 'mode...') // 新增
spinner.start() rm(path.join(config.build.assetsRoot, config.build.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
}) + '\n\n') if (stats.hasErrors()) {
console.log(chalk.red(' Build failed with errors.\n'))
process.exit(1)
} console.log(chalk.cyan(' Build 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'
))
})
})
(6)build下面的 webpack.base.conf.js
'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf') function resolve (dir) {
return path.join(__dirname, '..', dir)
} const createLintingRule = () => ({
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter'),
emitWarning: !config.dev.showEslintErrorsInOverlay
}
}) module.exports = {
context: path.resolve(__dirname, '../'),
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
// publicPath: process.env.NODE_ENV === 'production'
// ? config.build.assetsPublicPath
// : config.dev.assetsPublicPath // 注释原有
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: (process.env.NODE_ENV === 'testing' || process.env.NODE_ENV === 'development' ? config.build.assetsPublicPath : config.dev.assetsPublicPath) // 新增判断
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': resolve('src'),
}
},
module: {
rules: [
...(config.dev.useEslint ? [createLintingRule()] : []),
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('media/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
},
node: {
// prevent webpack from injecting useless setImmediate polyfill because Vue
// source contains it (although only uses it if it's native).
setImmediate: false,
// prevent webpack from injecting mocks to Node native modules
// that does not make sense for the client
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty'
}
}
(7)build下面的 webpack.prod.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 UglifyJsPlugin = require('uglifyjs-webpack-plugin') // const env = process.env.NODE_ENV === 'testing'
// ? require('../config/test.env')
// : require('../config/prod.env') // 注释原有
const env = config.build[process.env.env_config + 'Env'] // 新增 const webpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true,
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: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
'process.env': env,
'process.env.BASE_URL': JSON.stringify(process.env.BASE_URL), //增加此行 (可加可不加)
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_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: process.env.NODE_ENV === 'testing'
? 'index.html'
: config.build.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.build.assetsSubDirectory,
ignore: ['.*']
}
])
]
}) if (config.build.productionGzip) {
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,
minRatio: 0.8
})
)
} if (config.build.bundleAnalyzerReport) {
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
} module.exports = webpackConfig
(8)build下面的 utils.js
'use strict'
const path = require('path')
const config = require('../config')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const packageConfig = require('../package.json') exports.assetsPath = function (_path) {
const assetsSubDirectory = process.env.NODE_ENV === 'production'
? config.build.assetsSubDirectory
: config.dev.assetsSubDirectory return path.posix.join(assetsSubDirectory, _path)
} exports.cssLoaders = function (options) {
options = options || {} const cssLoader = {
loader: 'css-loader',
options: {
sourceMap: options.sourceMap
}
} const postcssLoader = {
loader: 'postcss-loader',
options: {
sourceMap: options.sourceMap
}
} // generate loader string to be used with extract text plugin
function generateLoaders (loader, loaderOptions) {
const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader] if (loader) {
loaders.push({
loader: loader + '-loader',
options: Object.assign({}, loaderOptions, {
sourceMap: options.sourceMap
})
})
} // Extract CSS when that option is specified
// (which is the case during production build)
if (options.extract) {
return ExtractTextPlugin.extract({
use: loaders,
fallback: 'vue-style-loader',
publicPath:'../../' // 新增配置 防止打包图片(如背景图片)路径报错
})
} else {
return ['vue-style-loader'].concat(loaders)
}
} // https://vue-loader.vuejs.org/en/configurations/extract-css.html
return {
css: generateLoaders(),
postcss: generateLoaders(),
less: generateLoaders('less'),
sass: generateLoaders('sass', { indentedSyntax: true }),
scss: generateLoaders('sass'),
stylus: generateLoaders('stylus'),
styl: generateLoaders('stylus')
}
} // Generate loaders for standalone style files (outside of .vue)
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
})
} return output
} exports.createNotifierCallback = () => {
const notifier = require('node-notifier') return (severity, errors) => {
if (severity !== 'error') return const error = errors[0]
const filename = error.file && error.file.split('!').pop() notifier.notify({
title: packageConfig.name,
message: severity + ': ' + error.name,
subtitle: filename || '',
icon: path.join(__dirname, 'logo.png')
})
}
}
(9)api下面的 axios.js
import axios from 'axios'
import qs from 'qs' // 生成一个 axios 实例
const instance = axios.create({
baseURL: process.env.BASE_URL, // api 的 base_url
timeout: 5000 // 请求 超时配置
}) // 请求 拦截器
instance.interceptors.request.use(config => {
config.withCredentials = true
if (config.headers['Content-Type'] === 'application/json') {
config.data = JSON.stringify(config.data)
}
if (config.headers['Content-Type'] === 'multipart/form-data') {
return config
}
if (config.method === 'post' || config.method === 'put' || config.method === 'delete') {
if (typeof (config.data) !== 'string') {
config.data = qs.stringify(config.data)
}
}
return config
}, error => {
Promise.reject(error)
}) // 响应 拦截器
axios.interceptors.response.use(response => {
// 对响应数据做处理
return response
}, error => {
// 对响应错误做处理
return Promise.reject(error)
}) export default instance
(10)api下面的 http.js
import instance from './axios'
// get请求
export function getList(params) {
return instance({
url: `/xxxx`,
method: 'get',
params
})
}
// post请求
export function getpostList(data) {
return instance({
url: '/xxx',
method: 'post',
headers: { 'Content-Type': 'application/json' },
data
})
}
(11)package.json配置
"scripts": {
"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
"start": "npm run dev",
"unit": "jest --config test/unit/jest.conf.js --coverage",
"e2e": "node test/e2e/runner.js",
"test": "npm run unit && npm run e2e",
"lint": "eslint --ext .js,.vue src test/unit test/e2e/specs",
"build": "node build/build.js",
"build:dev": "cross-env NODE_ENV=development env_config=dev node build/build.js", // 新增
"build:test": "cross-env NODE_ENV=testing env_config=test node build/build.js", // 新增
"build:prod": "cross-env NODE_ENV=production env_config=prod node build/build.js" // 新增
},
完整的分环境打包就完成了。。。。
执行对应的命令
1、cnpm/npm run build:dev ------本地包打包完成
2、cnpm/npm run build:test ------测试包打包完成
3、cnpm/npm run build:prod ------生产包打包完成
vue分环境打包配置不同命令的更多相关文章
- vue分环境打包配置方法一
直接上代码配置: 首先是config下面的文件修改 dev.env.js 'use strict' const merge = require('webpack-merge') const prod ...
- VUE 如何分环境打包(开发/测试/生产)配置
前言 之前小玲一直处于更新,迭代项目的状态,开发环境.测试环境.生产环境都是前辈配置好的,自己几乎没有配置过,这次做几个新项目时,面临着上线,需要分环境打包配置,于是在网上遨游了一会会,摸索着按照网上 ...
- vue3.0+vite+ts项目搭建-分环境打包(四)
分环境打包配置 新建.env.dev(或者.env) VITE_NODE_ENV = 'dev' VITE_HOST = 'http://local.host.com' 执行yarn dev ,控制台 ...
- 基于Vue + webpack + Vue-cli 实现分环境打包项目
需求由来:我公司项目上线发布至服务器分为三个环境分别为测试环境.预发布环境.生产环境:前期做法是项目通过脚步打包时由脚步把域名和后缀名之类的全部替换成要发布的环境所需要的,因为我公司的项目比较大由许许 ...
- 前端自动分环境打包(vue和ant design)
现实中的问题:有时候版本上线的时候,打包时忘记切换环境,将测试包推上正式服务器,那你就会被批了. 期望:在写打包的命令行的时候就觉得自己在打包正式版本,避免推包时候的,不确信自己的包是否正确. 既然有 ...
- Vue项目分环境打包的实现步骤
转:https://blog.csdn.net/xinzi11243094/article/details/80521878 方法一:亲测真的有效 在项目开发中,我们的项目一般分为开发版.测试版.Pr ...
- 使用Maven分环境打包:dev sit uat prod
使用Maven管理的项目,经常需要根据不同的环境打不同的包,因为环境不同,所需要的配置文件不同,比如database的连接信息,相关属性等等. 在Maven中,我们可以通过P参数和profiles元素 ...
- springboot分环境打包(maven动态选择环境)
分环境打包核心点:spring.profiles.active pom.xml中添加: <profiles> <profile> <id>dev</id> ...
- vue实现分环境打包步骤(给不同的环境配置相对应的打包命令)
在新建好的项目中,一般执行npm run build就是打包了,但此时只能打包到一个环境,不同环境需要配置不同的地址,可以手动更改接口的地址,也可以自行配置命令而不需要每次打包进行地址切换,步骤如下: ...
随机推荐
- Ubuntu 14.04中修复默认启用HDMI后没有声音的问题
声音问题在Ubuntu中是老生常谈了.先前我已经在修复Ubuntu中的“无声”问题一文中写到了多种方法,但是我在此正要谈及的声音问题跟在另外一篇文章中提到的有所不同. 因此,我安装了Ubuntu 14 ...
- # program once 用途 及与 ifndef使用异同
在头文件中用这种写法就是为了该头文件被重复包含时不会出现符合重定义的错误. 效果等同于 #ifndef __xxx__ #define __xxx__ ... #endi ...
- “MVC+Nhibernate+Jquery-EasyUI”信息发布系统 第二篇(数据库结构、登录窗口、以及主界面)
一.在上一篇文章中,主要说的就是把主框架搭建起来,并且Nhibernate能达到增删改查的地步.测试好之后再来看这篇文章,我的主框架相对来说简答一点,重点还是实现系统的功能,以及对Jquery-Eas ...
- E20190420-hm
impact n. 巨大影响; 强大作用; 撞击; 冲撞; 冲击力; v. (对某事物) 有影响,有作用; 冲击; 撞击; incident n. 发生的事情(尤指不寻常的或讨厌的); 严 ...
- Git入门 时光穿梭鸡 版本回退 工作区 暂存区
分布式集中式 CVS及SVN都是集中式的版本控制系统 , 而Git是分布式版本控制系统 集中式版本控制系统,版本库是集中存放在中央服务器的, 而干活的时候,用的都是自己的电脑,所以要先从中央服务器取得 ...
- 用js判断屏幕的宽度,改变html字体大小用rem布局
if (document.documentElement.clientWidth > 600) {//页面宽度大于600px让其宽度等于600px,字体大小等于60px,居中 document. ...
- [Xcode 实际操作]六、媒体与动画-(16)实现音乐的背景播放
目录:[Swift]Xcode实际操作 本文将演示音乐的背景播放功能 打开项目信息配置文件[info.plist]. 需要在配置文件中进行一些操作,使程序支持音乐的背景播放. 点击鼠标右键,弹出右键菜 ...
- 了解HTTP协议和TCP协议
HTTP(超文本传输协议),互联网上应用最为广泛的一种网络协议.所有的www文件都必须遵守这个标准.HTTP是一个客户端和服务端请求和应答的标准(TCP):客户通过浏览器发起一个到服务器上指定端口的H ...
- 使用docker搭建项目环境
# 清屏 clear # 查看当前文件夹下的列表 ls # 跳目录 cd ~ 代表当前用户文件夹 cd / 代表根目录 cd..返回上一级目录 cd #sudo 使用超级管理员创建文件夹 不加sudo ...
- servlet连接mysql数据库和oracle数据库
连接mysql数据库 package dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.P ...