淺談Vue-cli 命令行工具分析
Vue.js 提供一個(gè)官方命令行工具,可用于快速搭建大型單頁(yè)應(yīng)用。vue-webpack-boilerplate,官方定義為:
full-featured Webpack setup with hot-reload, lint-on-save, unit testing & css extraction.
目錄結(jié)構(gòu):
├── README.md ├── build │ ├── build.js │ ├── utils.js │ ├── vue-loader.conf.js │ ├── webpack.base.conf.js │ ├── webpack.dev.conf.js │ └── webpack.prod.conf.js ├── config │ ├── dev.env.js │ ├── index.js │ └── prod.env.js ├── index.html ├── package.json ├── src │ ├── App.vue │ ├── assets │ │ └── logo.png │ ├── components │ │ └── Hello.vue │ └── main.js └── static
config 環(huán)境配置
config 配置文件用來(lái)配置 devServer 的相關(guān)設(shè)定,通過(guò)配置 NODE_ENV 來(lái)確定使用何種模式(開(kāi)發(fā)、生產(chǎn)、測(cè)試或其他)
config |- index.js #配置文件 |- dev.env.js #開(kāi)發(fā)模式 |- prod.env.js #生產(chǎn)模式
index.js
'use strict'
const path = require('path');
module.exports = {
dev: {
// 路徑
assetsSubDirectory: 'static', // path:用來(lái)存放打包后文件的輸出目錄
assetsPublicPath: '/', // publicPath:指定資源文件引用的目錄
proxyTable: {}, // 代理示例: proxy: [{context: ["/auth", "/api"],target: "http://localhost:3000",}]
// 開(kāi)發(fā)服務(wù)器變量設(shè)置
host: 'localhost',
port: 8080,
autoOpenBrowser: true, // 自動(dòng)打開(kāi)瀏覽器devServer.open
errorOverlay: true, // 瀏覽器錯(cuò)誤提示 devServer.overlay
notifyOnErrors: true, // 配合 friendly-errors-webpack-plugin
poll: true, // 使用文件系統(tǒng)(file system)獲取文件改動(dòng)的通知devServer.watchOptions
// source map
cssSourceMap: false, // develop 下不生成 sourceMap
devtool: 'eval-source-map' // 增強(qiáng)調(diào)試 可能的推薦值:eval, eval-source-map(推薦), cheap-eval-source-map, cheap-module-eval-source-map 詳細(xì):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, // 默認(rèn) false
productionGzipExtensions: ['js', 'css'],
// source map
productionSourceMap: true, // production 下是生成 sourceMap
devtool: '#source-map' // devtool: 'source-map' ?
}
}
dev.env.js
'use strict'
const merge = require('webpack-merge');
const prodEnv = require('./prod.env');
module.exports = merge(prodEnv, {
NODE_ENV: '"development"'
});
prod.env.js
'use strict'
module.exports = {
NODE_ENV: '"production"'
};
build Webpack配置
build |- utils.js #代碼段 |- webpack.base.conf.js #基礎(chǔ)配置文件 |- webpack.dev.conf.js #開(kāi)發(fā)模式配置文件 |- webpack.prod.conf.js #生產(chǎn)模式配置文件 |- build.js #編譯入口
實(shí)用代碼段 utils.js
const config = require('../config')
const path = require('path')
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] // 設(shè)置默認(rèn)loader
if (loader) {
loaders.push({
loader: loader + '-loader',
options: Object.assign({}, loaderOptions, { // 生成 options 對(duì)象
sourceMap: options.sourceMap
})
})
}
// 生產(chǎn)模式中提取css
if (options.extract) { // 如果 options 中的 extract 為 true 配合生產(chǎn)模式
return ExtractTextPlugin.extract({
use: loaders,
fallback: 'vue-style-loader' // 默認(rèn)使用 vue-style-loader
})
} else {
return ['vue-style-loader'].concat(loaders)
}
}
return { // 返回各種 loaders 對(duì)象
css: generateLoaders(),
postcss: generateLoaders(),
less: generateLoaders('less'),
// 示例:[
// { loader: 'css-loader', options: { sourceMap: true/false } },
// { loader: 'postcss-loader', options: { sourceMap: true/false } },
// { loader: 'less-loader', options: { sourceMap: true/false } },
// ]
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'); // 發(fā)送跨平臺(tái)通知系統(tǒng)
return (severity, errors) => {
// 當(dāng)前設(shè)定是只有出現(xiàn) error 錯(cuò)誤時(shí)觸發(fā) notifier 發(fā)送通知
if (severity !== 'error') { return } // 嚴(yán)重程度可以是 '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') // 通知圖標(biāo)
})
}
}
基礎(chǔ)配置文件 webpack.base.conf.js
基礎(chǔ)的 webpack 配置文件主要根據(jù)模式定義了入口出口,以及處理 vue, babel 等的各種模塊,是最為基礎(chǔ)的部分。其他模式的配置文件以此為基礎(chǔ)通過(guò) webpack-merge 合并。
'use strict'
const path = require('path');
const utils = require('./utils');
const config = require('../config');
function resolve(dir) {
return path.join(__dirname, '..', dir);
}
module.exports = {
context: path.resolve(__dirname, '../'), // 基礎(chǔ)目錄
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot, // 默認(rèn)'../dist'
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath // 生產(chǎn)模式publicpath
: config.dev.assetsPublicPath // 開(kāi)發(fā)模式publicpath
},
resolve: { // 解析確定的拓展名,方便模塊導(dǎo)入
extensions: ['.js', '.vue', '.json'],
alias: { // 創(chuàng)建別名
'vue$': 'vue/dist/vue.esm.js',
'@': resolve('src') // 如 '@/components/HelloWorld'
}
},
module: {
rules: [{
test: /\.vue$/, // vue 要在babel之前
loader: 'vue-loader',
options: vueLoaderConfig //可選項(xiàng): vue-loader 選項(xiàng)配置
},{
test: /\.js$/, // babel
loader: 'babel-loader',
include: [resolve('src')]
},{ // url-loader 文件大小低于指定的限制時(shí),可返回 DataURL,即base64
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, // url-loader 圖片
loader: 'url-loader',
options: { // 兼容性問(wèn)題需要將query換成options
limit: 10000, // 默認(rèn)無(wú)限制
name: utils.assetsPath('img/[name].[hash:7].[ext]') // hash:7 代表 7 位數(shù)的 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',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
},
node: { // 是否 polyfill 或 mock
setImmediate: false,
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty'
}
}
開(kāi)發(fā)模式配置文件 webpack.dev.conf.js
開(kāi)發(fā)模式的配置文件主要引用了 config 對(duì)于 devServer 的設(shè)定,對(duì) css 文件的處理,使用 DefinePlugin 判斷是否生產(chǎn)環(huán)境,以及其他一些插件。
'use strict'
const webpack = require('webpack');
const config = require('../config');
const merge = require('webpack-merge');
const baseWebpackConfig = require('./webpack.base.conf');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const portfinder = require('portfinder'); // 自動(dòng)檢索下一個(gè)可用端口
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin'); // 友好提示錯(cuò)誤信息
const devWebpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
// 自動(dòng)生成了 css, postcss, less 等規(guī)則,與自己一個(gè)個(gè)手寫一樣,默認(rèn)包括了 css 和 postcss 規(guī)則
},
devtool: config.dev.devtool,// 添加元信息(meta info)增強(qiáng)調(diào)試
// devServer 在 /config/index.js 處修改
devServer: {
clientLogLevel: 'warning', // console 控制臺(tái)顯示的消息,可能的值有 none, error, warning 或者 info
historyApiFallback: true, // History API 當(dāng)遇到 404 響應(yīng)時(shí)會(huì)被替代為 index.html
hot: true, // 模塊熱替換
compress: true, // gzip
host: process.env.HOST || config.dev.host, // process.env 優(yōu)先
port: process.env.PORT || config.dev.port, // process.env 優(yōu)先
open: config.dev.autoOpenBrowser, // 是否自動(dòng)打開(kāi)瀏覽器
overlay: config.dev.errorOverlay ? { // warning 和 error 都要顯示
warnings: true,
errors: true,
} : false,
publicPath: config.dev.assetsPublicPath, // 配置publicPath
proxy: config.dev.proxyTable, // 代理
quiet: true, // 控制臺(tái)是否禁止打印警告和錯(cuò)誤 若使用 FriendlyErrorsPlugin 此處為 true
watchOptions: {
poll: config.dev.poll, // 文件系統(tǒng)檢測(cè)改動(dòng)
}
},
plugins: [
new webpack.DefinePlugin({
'process.env': require('../config/dev.env') // 判斷生產(chǎn)環(huán)境或開(kāi)發(fā)環(huán)境
}),
new webpack.HotModuleReplacementPlugin(), // 熱加載
new webpack.NamedModulesPlugin(), // 熱加載時(shí)直接返回更新的文件名,而不是id
new webpack.NoEmitOnErrorsPlugin(), // 跳過(guò)編譯時(shí)出錯(cuò)的代碼并記錄下來(lái),主要作用是使編譯后運(yùn)行時(shí)的包不出錯(cuò)
new HtmlWebpackPlugin({ // 該插件可自動(dòng)生成一個(gè) html5 文件或使用模板文件將編譯好的代碼注入進(jìn)去
filename: 'index.html',
template: 'index.html',
inject: true // 可能的選項(xiàng)有 true, 'head', 'body', false
}),
]
})
module.exports = new Promise((resolve, reject) => {
portfinder.basePort = process.env.PORT || config.dev.port; // 獲取當(dāng)前設(shè)定的端口
portfinder.getPort((err, port) => {
if (err) { reject(err) } else {
process.env.PORT = port; // process 公布端口
devWebpackConfig.devServer.port = port; // 設(shè)置 devServer 端口
devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({ // 錯(cuò)誤提示插件
compilationSuccessInfo: {
messages: [`Your application is running here: http://${config.dev.host}:${port}`],
},
onErrors: config.dev.notifyOnErrors ? utils.createNotifierCallback() : undefined
}))
resolve(devWebpackConfig);
}
})
})
生產(chǎn)模式配置文件 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 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 方法內(nèi)的 generateLoaders 函數(shù)
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: [
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',
template: 'index.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
},
chunksSortMode: 'dependency' // 按 dependency 的順序引入
}),
new webpack.HashedModuleIdsPlugin(), // 根據(jù)模塊的相對(duì)路徑生成一個(gè)四位數(shù)的 hash 作為模塊 id
new webpack.optimize.ModuleConcatenationPlugin(), // 預(yù)編譯所有模塊到一個(gè)閉包中
// 拆分公共模塊
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
}),
// 拷貝靜態(tài)文檔
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 // 最小比例達(dá)到 .8 時(shí)才壓縮
})
)
}
if (config.build.bundleAnalyzerReport) { // 可視化分析包的尺寸
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
webpackConfig.plugins.push(new BundleAnalyzerPlugin());
}
module.exports = webpackConfig;
build.js 編譯入口
'use strict'
process.env.NODE_ENV = 'production'; // 設(shè)置當(dāng)前環(huán)境為生產(chǎn)環(huán)境
const ora = require('ora'); //loading...進(jìn)度條
const rm = require('rimraf'); //刪除文件 'rm -rf'
const chalk = require('chalk'); //stdout顏色設(shè)置
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;
// 刪除完成回調(diào)函數(shù)內(nèi)執(zhí)行編譯
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(' 編譯失敗出現(xiàn)錯(cuò)誤.\n'));
process.exit(1);
}
//完成
console.log(chalk.cyan(' 編譯成功.\n'))
console.log(chalk.yellow(
' file:// 無(wú)用,需http(s)://.\n'
))
})
})
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vant steps流程圖的圖標(biāo)使用slot自定義方式
這篇文章主要介紹了vant steps流程圖的圖標(biāo)使用slot自定義方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06
vue,angular,avalon這三種MVVM框架優(yōu)缺點(diǎn)
本文給大家具體分析了下vue,angular,avalon這三種MVVM框架優(yōu)缺點(diǎn),十分的細(xì)致全面,有需要的小伙伴可以參考下2016-04-04
前端框架Vue父子組件數(shù)據(jù)雙向綁定的實(shí)現(xiàn)
Vue項(xiàng)目中經(jīng)常使用到組件之間的數(shù)值傳遞,實(shí)現(xiàn)的方法很多,但是原理上基本大同小異。這篇文章將給大家介紹Vue 父子組件數(shù)據(jù)單向綁定與Vue 父子組件數(shù)據(jù)雙向綁定的對(duì)比從而認(rèn)識(shí)雙向綁定2021-09-09
vue項(xiàng)目使用websocket連接問(wèn)題及解決
這篇文章主要介紹了vue項(xiàng)目使用websocket連接問(wèn)題及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-10-10
Vue零基礎(chǔ)入門之模板語(yǔ)法與數(shù)據(jù)綁定及Object.defineProperty方法詳解
這篇文章主要介紹了Vue初學(xué)基礎(chǔ)中的模板語(yǔ)法、數(shù)據(jù)綁定、Object.defineProperty方法等基礎(chǔ),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-09-09
vue3使用pdf.js來(lái)預(yù)覽文件的操作步驟(本地文件測(cè)試)
這篇文章主要介紹了vue3使用pdf.js來(lái)預(yù)覽文件的操作步驟(本地文件測(cè)試),文中通過(guò)代碼示例和圖文結(jié)合的方式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-05-05
vue自定義插件封裝,實(shí)現(xiàn)簡(jiǎn)易的elementUi的Message和MessageBox的示例
這篇文章主要介紹了vue自定義插件封裝,實(shí)現(xiàn)簡(jiǎn)易的elementUi的Message和MessageBox的示例,幫助大家更好的理解和使用vue框架,感興趣的朋友可以了解下2020-11-11

