浅谈Vue-cli 命令行工具分析

Vue.js 提供一个官方命令行工具,可用于快速搭建大型单页应用。vue-webpack-boilerplate,官方定义为:

full-featured Webpack setup with hot-reload,lint-on-save,unit testing & css extraction.

目录结构:

config 环境配置

config 配置文件用来配置 devServer 的相关设定,通过配置 NODE_ENV 来确定使用何种模式(开发、生产、测试或其他)

index.js

module.exports = {
dev: {

// 路径
assetsSubDirectory: 'static',// path:用来存放打包后文件的输出目录
assetsPublicPath: '/',// publicPath:指定资源文件引用的目录
proxyTable: {},// 代理示例: proxy: [{context: ["/auth","/api"],target: "http://localhost:3000",}]

// 开发服务器变量设置
host: 'localhost',port: 8080,autoOpenBrowser: true,// 自动打开浏览器devServer.open
errorOverlay: true,// 浏览器错误提示 devServer.overlay
notifyOnErrors: true,// 配合 friendly-errors-webpack-plugin
poll: true,// 使用文件系统(file system)获取文件改动的通知devServer.watchOptions

// source map
cssSourceMap: false,// develop 下不生成 sourceMap
devtool: 'eval-source-map' // 增强调试 可能的推荐值:eval,eval-source-map(推荐),cheap-eval-source-map,cheap-module-eval-source-map 详细:https://doc.webpack-china.org/configuration/devtool
},build: {
// index模板文件
index: path.resolve(dirname,'../dist/index.html'),// 路径
assetsRoot: path.resolve(
dirname,'../dist'),assetsSubDirectory: 'static',assetsPublicPath: '/',// bundleAnalyzerReport
bundleAnalyzerReport: process.env.npm_config_report,// Gzip
productionGzip: false,// 默认 false
productionGzipExtensions: ['js','css'],// source map
productionSourceMap: true,// production 下是生成 sourceMap
devtool: '#source-map' // devtool: 'source-map' ?
}
}

dev.env.js

module.exports = merge(prodEnv,{
NODE_ENV: '"development"'
});
prod.env.js
'use strict'
module.exports = {
NODE_ENV: '"production"'
};

build Webpack配置

实用代码段 utils.js

exports.assetsPath = function (_path) {
const assetsSubDirectory = process.env.NODE_ENV === 'production'
? config.build.assetsSubDirectory // 'static'
: config.dev.assetsSubDirectory
return path.posix.join(assetsSubDirectory,_path) // posix方法修正路径
}

exports.cssLoaders = function (options) { // 示例: ({ sourceMap: config.dev.cssSourceMap,usePostCSS: true })
options = options || {};

// cssLoader
const cssLoader = {
loader: 'css-loader',options: { sourceMap: options.sourceMap }
}
// postcssLoader
var postcssLoader = {
loader: 'postcss-loader',options: { sourceMap: options.sourceMap }
}

// 生成 loader
function generateLoaders (loader,loaderOptions) {
const loaders = options.usePostCSS ? [cssLoader,postcssLoader] : [cssLoader] // 设置默认loader
if (loader) {
loaders.push({
loader: loader + '-loader',options: Object.assign({},loaderOptions,{ // 生成 options 对象
sourceMap: options.sourceMap
})
})
}

// 生产模式中提取css
if (options.extract) { // 如果 options 中的 extract 为 true 配合生产模式
return ExtractTextPlugin.extract({
use: loaders,fallback: 'vue-style-loader' // 默认使用 vue-style-loader
})
} else {
return ['vue-style-loader'].concat(loaders)
}
}

return { // 返回各种 loaders 对象
css: generateLoaders(),postcss: generateLoaders(),less: generateLoaders('less'),// 示例:[
// { loader: 'css-loader',options: { sourceMap: true/false } },// { loader: 'postcss-loader',// { loader: 'less-loader',// ]
sass: generateLoaders('sass',{ indentedSyntax: true }),scss: generateLoaders('sass'),stylus: generateLoaders('stylus'),styl: generateLoaders('stylus')
}
}

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
})
// 示例:
// {
// test: new RegExp(\.less$),// use: {
// loader: 'less-loader',options: { sourceMap: true/false }
// }
// }
}
return output
}

exports.createNotifierCallback = function () { // 配合 friendly-errors-webpack-plugin
// 基本用法:notifier.notify('message');
const notifier = require('node-notifier'); // 发送跨平台通知系统

return (severity,errors) => {
// 当前设定是只有出现 error 错误时触发 notifier 发送通知
if (severity !== 'error') { return } // 严重程度可以是 'error' 或 'warning'
const error = errors[0]

const filename = error.file && error.file.split('!').pop();
notifier.notify({
title: pkg.name,message: severity + ': ' + error.name,subtitle: filename || ''
// icon: path.join(__dirname,'logo.png') // 通知图标
})
}
}

基础配置文件 webpack.base.conf.js

基础的 webpack 配置文件主要根据模式定义了入口出口,以及处理 vue,babel 等的各种模块,是最为基础的部分。其他模式的配置文件以此为基础通过 webpack-merge 合并。

function resolve(dir) {
return path.join(__dirname,'..',dir);
}

module.exports = {
context: path.resolve(__dirname,'../'),// 基础目录
entry: {
app: './src/main.js'
},output: {
path: config.build.assetsRoot,// 默认'../dist'
filename: '[name].js',publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath // 生产模式publicpath
: config.dev.assetsPublicPath // 开发模式publicpath
},resolve: { // 解析确定的拓展名,方便模块导入
extensions: ['.js','.vue','.json'],alias: { // 创建别名
'vue$': 'vue/dist/vue.esm.js','@': resolve('src') // 如 '@/components/HelloWorld'
}
},module: {
rules: [{
test: /.vue$/,// vue 要在babel之前
loader: 'vue-loader',options: vueLoaderConfig //可选项: vue-loader 选项配置
},{
test: /.js$/,// babel
loader: 'babel-loader',include: [resolve('src')]
},{ // url-loader 文件大小低于指定的限制时,可返回 DataURL,即base64
test: /.(png|jpe?g|gif|svg)(\?.)?$/,// url-loader 图片
loader: 'url-loader',options: { // 兼容性问题需要将query换成options
limit: 10000,// 默认无限制
name: utils.assetsPath('img/[name].[hash:7].[ext]') // hash:7 代表 7 位数的 hash
}
},{
test: /.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.
)?$/,// url-loader 音视频
loader: 'url-loader',options: {
limit: 10000,name: utils.assetsPath('media/[name].[hash:7].[ext]')
}
},{
test: /.(woff2?|eot|ttf|otf)(\?.*)?$/,// url-loader 字体
loader: 'url-loader',name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
},node: { // 是否 polyfill 或 mock
setImmediate: false,dgram: 'empty',fs: 'empty',net: 'empty',tls: 'empty',child_process: 'empty'
}
}

开发模式配置文件 webpack.dev.conf.js

开发模式的配置文件主要引用了 config 对于 devServer 的设定,对 css 文件的处理,使用 DefinePlugin 判断是否生产环境,以及其他一些插件。

const devWebpackConfig = merge(baseWebpackConfig,{
module: {
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap,usePostCSS: true })
// 自动生成了 css,postcss,less 等规则,与自己一个个手写一样,默认包括了 css 和 postcss 规则
},devtool: config.dev.devtool,// 添加元信息(meta info)增强调试

// devServer 在 /config/index.js 处修改
devServer: {
clientLogLevel: 'warning',// console 控制台显示的消息,可能的值有 none,error,warning 或者 info
historyApiFallback: true,// History API 当遇到 404 响应时会被替代为 index.html
hot: true,// 模块热替换
compress: true,// gzip
host: process.env.HOST || config.dev.host,// process.env 优先
port: process.env.PORT || config.dev.port,// process.env 优先
open: config.dev.autoOpenBrowser,// 是否自动打开浏览器
overlay: config.dev.errorOverlay ? { // warning 和 error 都要显示
warnings: true,errors: true,} : false,publicPath: config.dev.assetsPublicPath,// 配置publicPath
proxy: config.dev.proxyTable,// 代理
quiet: true,// 控制台是否禁止打印警告和错误 若使用 FriendlyErrorsPlugin 此处为 true
watchOptions: {
poll: config.dev.poll,// 文件系统检测改动
}
},plugins: [
new webpack.DefinePlugin({
'process.env': require('../config/dev.env') // 判断生产环境或开发环境
}),new webpack.HotModuleReplacementPlugin(),// 热加载
new webpack.NamedModulesPlugin(),// 热加载时直接返回更新的文件名,而不是id
new webpack.NoEmitOnErrorsPlugin(),// 跳过编译时出错的代码并记录下来,主要作用是使编译后运行时的包不出错
new HtmlWebpackPlugin({ // 该插件可自动生成一个 html5 文件或使用模板文件将编译好的代码注入进去
filename: 'index.html',template: 'index.html',inject: true // 可能的选项有 true,'head','body',false
}),]
})

module.exports = new Promise((resolve,reject) => {
portfinder.basePort = process.env.PORT || config.dev.port; // 获取当前设定的端口
portfinder.getPort((err,port) => {
if (err) { reject(err) } else {
process.env.PORT = port; // process 公布端口
devWebpackConfig.devServer.port = port; // 设置 devServer 端口

devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({ // 错误提示插件
compilationSuccessInfo: {
messages: [Your application is running here: http://${config.dev.host}:${port}],},onErrors: config.dev.notifyOnErrors ? utils.createNotifierCallback() : undefined
}))

resolve(devWebpackConfig);
}
})
})

生产模式配置文件 webpack.prod.conf.js

const env = process.env.NODE_ENV === 'production'
? require('../config/prod.env')
: require('../config/dev.env')

const webpackConfig = merge(baseWebpackConfig,{
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,// production 下生成 sourceMap
extract: true,// util 中 styleLoaders 方法内的 generateLoaders 函数
usePostCSS: true
})
},devtool: config.build.productionSourceMap ? config.build.devtool : false,filename: utils.assetsPath('js/[name].[chunkhash].js'),chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
},plugins: [
new webpack.DefinePlugin({ 'process.env': env }),new webpack.optimize.UglifyJsPlugin({ // js 代码压缩还可配置 include,cache 等,也可用 babel-minify
compress: { warnings: false },sourceMap: config.build.productionSourceMap,parallel: true // 充分利用多核cpu
}),// 提取 js 文件中的 css
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css'),allChunks: false,}),// 压缩提取出的css
new OptimizeCSSPlugin({
cssProcessorOptions: config.build.productionSourceMap
? { safe: true,map: { inline: false } }
: { safe: true }
}),// 生成 html
new HtmlWebpackPlugin({
filename: process.env.NODE_ENV === 'production'
? config.build.index
: 'index.html',inject: true,minify: {
removeComments: true,collapseWhitespace: true,removeAttributeQuotes: true
},chunksSortMode: 'dependency' // 按 dependency 的顺序引入
}),new webpack.HashedModuleIdsPlugin(),// 根据模块的相对路径生成一个四位数的 hash 作为模块 id
new webpack.optimize.ModuleConcatenationPlugin(),// 预编译所有模块到一个闭包中
// 拆分公共模块
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',minChunks: function (module) {
return (
module.resource &&
/.js$/.test(module.resource) &&
module.resource.indexOf(
path.join(__dirname,'../node_modules')
) === 0
)
}
}),new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',minChunks: Infinity
}),new webpack.optimize.CommonsChunkPlugin({
name: 'app',async: 'vendor-async',children: true,minChunks: 3
}),// 拷贝静态文档
new CopyWebpackPlugin([{
from: path.resolve(__dirname,'../static'),to: config.build.assetsSubDirectory,ignore: ['.*']
}])]
})

if (config.build.productionGzip) { // gzip 压缩
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,// 10kb 以上大小的文件才压缩
minRatio: 0.8 // 最小比例达到 .8 时才压缩
})
)
}

if (config.build.bundleAnalyzerReport) { // 可视化分析包的尺寸
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
webpackConfig.plugins.push(new BundleAnalyzerPlugin());
}

module.exports = webpackConfig;

build.js 编译入口

process.env.NODE_ENV = 'production'; // 设置当前环境为生产环境
const ora = require('ora'); //loading...进度条
const rm = require('rimraf'); //删除文件 'rm -rf'
const chalk = require('chalk'); //stdout颜色设置
const webpack = require('webpack');
const path = require('path');
const config = require('../config');
const webpackConfig = require('./webpack.prod.conf');

const spinner = ora('正在编译...');
spinner.start();

// 清空文件夹
rm(path.join(config.build.assetsRoot,config.build.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');

//error
if (stats.hasErrors()) {
console.log(chalk.red(' 编译失败出现错误.\n'));
process.exit(1);
}

//完成
console.log(chalk.cyan(' 编译成功.\n'))
console.log(chalk.yellow(
' file:// 无用,需http(s)://.\n'
))
})

})

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


https://segmentfault.com/a/1190000022018995 https://www.jianshu.com/p/8c3599dda094 vuex教程中,有这样一句话和这样一段代码: 实践中,我们会经常用到 ES2015 的参数解构来简化代码(特别是我们需要调用commi
ES6 (ECMAScript 6)中的模块是一个包含 JavaScript 代码的文件,在这个模块中所有的变量都对其他模块是不可见的,除非我们导出它。 ES6的模块系统大致分为导出(export)和导入(import)两个模块。 1、模块导出(export) 可以 导出 所有的最外层 函数 、 类
from https://mp.weixin.qq.com/s/-rc1lYYlsfx-wR4mQmIIQQ Vue知识点汇总(含Vue3) 一、Vue 基础 1. Vue的基本原理 当一个Vue实例创建时,Vue会遍历data中的属性,用 Object.defineProperty(vue3.0使
D:\Temp>npm init vite@latest vue3study --template vuenpm ERR! code ETIMEDOUTnpm ERR! errno ETIMEDOUTnpm ERR! network request to https://registry.np
文章浏览阅读1.2k次。最近自己从零撸起的甘特图组件需要子组件的滚动条同步滚动这就涉及到子组件之间的互相通信,通过 消息总线可以达到我们的需求 ,首先建立一个标志位,拖动左边滚动条的时候,右边的滚动条事件不处理,反之拖动右边滚动条时,左边的滚动条事件不做处理,建立一个公共的变量用于两者的互斥store.jsimport Vue from 'vue'export let store = Vue.observable({ scrollFlag: true})export let mutations =.._vue 能不能同时有两个滚动事件
文章浏览阅读3.3k次,点赞3次,收藏16次。静默打印是什么?简单来说就是不需要用户点击"打印",自动去打印,但是使用浏览器web打印不可避免的要弹出以下画面面对这种问题也只能用"富客户端"技术来解决,在浏览器的沙盒安全模型中无法做到,那么只能使用插件的技术,这个我们就不自己花力气去做了,我找来了 lodop 这个免费的打印组件,功能还是挺强大的,下载下图的发行包解压后安装下图两个exe如果你的系统是64位的,可以安装install_lodop64.exe上图的LodopFuncs.js 是客户端要使用的核心库文件..._this.$getlodop().then((lodop) =>{
文章浏览阅读1.7k次。个人觉得大屏展示其实很简单,噱头多过技术含量,下面使用了 DataV (不是阿里的那个DataV哈,具体链接在这里)开发了一个大屏展示,使用了css flex弹性布局,使用了DataV的一些比较酷炫的边框(SVG写的),基本上功能没有全部完成,但是模子已经刻出来了,只是后端推送的内容没有全部写出来前端<template> <dv-full-screen-container class="screen-container"> <div class="ti_用signalr做一个简单的实时大屏显示
文章浏览阅读3.4k次,点赞3次,收藏10次。【说明】导入的Excel 字体颜色和背景色只能识别【标准色】,别的如"主题颜色",exceljs 解析出来不是颜色值。导入的样式包括字体,字号,列宽,合并单元格,【部分能识别】的背景色,文字颜色。导入到 x-data-spreadsheet 如下图。原Excel样式如下。_x-data-spreadsheet
文章浏览阅读1.7k次。之前参考某文章把 router-view 放在 el-tab-pane 外面都不起作用,问题根本不是出在 el-tab-pane,而是v-for 里面有多个route-view , keep-alive 时 tab 并未销毁掉,而是缓存隐藏了起来。需要把 router-view 的 name 与路由的 index.js 名称对应起来。之前参照很多文章修改试图修正这个问题,结果都徒劳,终于让我找到。我做了如下修改,主页面 main.vue。_el-tab-pane 后面接router-view
文章浏览阅读533次。今天在一台虚拟机上面运行老项目,报各种类型上图的错误提示,一开始还以为是less的问题,结果一个个装完还是报错,后面又说webpack, webpack cli有问题,头有点大了,google 一下,发现一个命令。讨论这个命令的文章,可以了解一下。运行以后终于出现了期待已久的。_npm install 忽略依赖
文章浏览阅读8k次,点赞3次,收藏12次。从这篇文章得到启发先定义一个组件从外部接收Template,然后在组件里调用<template > <div ref="markedContent"></div></template><script>import Vue from 'vue/dist/vue.esm.js'export default { name: 'wf-marked-content', props: ['content'], mounte.._vue components 动态传入模板
文章浏览阅读5.4k次。参考上一篇知识开发的一个功能,制作一个打印模板的管理模块,如下(就是保存froala编辑后的html文本,其中包括Vue的Template,这样我们可以利用Vue的模板的优势来动态绑定一些数据源进行HTML的打印,基本上跟过去水晶报表做一个模板再绑定数据源的方法异曲同工)在 main.js 里引用 froala 组件// Import and use Vue Froala lib.import VueFroala from 'vue-froala-wysiwyg'// 引入 Fr.._vue设计网页打印模板
文章浏览阅读992次。计划是这样,公司的项目一直在持续改动,安装包总是需要频繁生成新的,由此我想到了"持续集成"!有自动化工具不用,岂不可惜?这周的主要时间就用来学习CruiseControl.Net全面实现持续集成_怎么在vue的 script部分使用 eldigloa
文章浏览阅读1.2k次。其实Element UI 只用了文字提示的 el-tooltip 组件,不喜欢可以去掉,不记得是从哪拿到的原始代码,我给加了高亮渐变显示,图标,和拖拽时只能拖拽图标的位置,效果如上图,可以水平方向拖动,也可以垂直方向拖动。样式是less写的,css写嵌套样式太繁琐了。拿来主义,改造有理!下面贴代码<template> <div ref="splitPane" class="split-pane" :class="direction" :"{ fl..._element ui拉条样式
文章浏览阅读953次,点赞2次,收藏2次。接上一篇,这次加入的是从x-speadsheet导出Excel,并且带有x-speadsheet中的样式,重点关注 exportExcel 这个方法,我加入了 tinycolor 这个库用来翻译颜色值,值得注意的是, exceljs的颜色值是 argb 不是 rgba,一定不要弄混了a 是代表的透明度放在最前面_x-data-spreadsheet 导出
文章浏览阅读5.5k次,点赞2次,收藏21次。尝试了两个连线库 jsplumb 和 leadline ,其实两个库都很强大,但是基于个人使用的习惯,决定还是用 leadline ,在Vue 下我使用它的一个包装库 leader-line-vue 下面是上图的连接线示例代码,连接线很轻松的就实现了一个渐变效果..._vue 连线
文章浏览阅读4.2k次,点赞2次,收藏5次。首先官网推荐的安装方法没有生成dist文件,导致样式表等这些文件并没有生成npm install element-plus --save以上方法是有问题的,如果不幸执行了上面的命令,那么先执行卸载npm uninstall element-plus删除 main.js文件对element ui的引用,输入以下命令vue add element-plus..._elementui3.0
文章浏览阅读3.1k次。如上图,下面贴代码<template> <div> <el-date-picker size="large" style ="width:120px" v-model="selectYear" format="yyyy 年" value-format="yyyy" type="year" :clearable = "false" placeholder="选择年">.._vue多选周
文章浏览阅读1.8k次,点赞6次,收藏6次。经过 2021年的一个春节,从年前到现在,大致撸出一个 甘特图,进度条是用SVG画的,使用了几个工具库 (interactjs 用来处理拖拽和修改尺寸,snap.svg 用来处理 svg 的dom 操作,moment.js用来处理时间的操作),其他没有依赖任何的UI组件,目前初见雏形,还比较粗糙,后面会不断更新源码地址点击期间也摸索了怎么把vs code的项目上传到 GitHub 上面进行源代码的管理,基本上是参考的这篇文章做的..._vue gantt demo
文章浏览阅读2.1k次。接上两篇vue 下使用 exceljs + x-spreadsheet 带样式导入Excelvue 下使用 exceljs + x-spreadsheet 带样式导出Excel下面封装好一个组件调用组件的页面效果如图,目前“导出Json”还没有做_x-spreadsheet导入导出