<span id="mktg5"></span>

<i id="mktg5"><meter id="mktg5"></meter></i>

        <label id="mktg5"><meter id="mktg5"></meter></label>
        最新文章專題視頻專題問答1問答10問答100問答1000問答2000關鍵字專題1關鍵字專題50關鍵字專題500關鍵字專題1500TAG最新視頻文章推薦1 推薦3 推薦5 推薦7 推薦9 推薦11 推薦13 推薦15 推薦17 推薦19 推薦21 推薦23 推薦25 推薦27 推薦29 推薦31 推薦33 推薦35 推薦37視頻文章20視頻文章30視頻文章40視頻文章50視頻文章60 視頻文章70視頻文章80視頻文章90視頻文章100視頻文章120視頻文章140 視頻2關鍵字專題關鍵字專題tag2tag3文章專題文章專題2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章專題3
        問答文章1 問答文章501 問答文章1001 問答文章1501 問答文章2001 問答文章2501 問答文章3001 問答文章3501 問答文章4001 問答文章4501 問答文章5001 問答文章5501 問答文章6001 問答文章6501 問答文章7001 問答文章7501 問答文章8001 問答文章8501 問答文章9001 問答文章9501
        當前位置: 首頁 - 科技 - 知識百科 - 正文

        淺談Vue-cli 命令行工具分析

        來源:懂視網(wǎng) 責編:小采 時間:2020-11-27 22:25:10
        文檔

        淺談Vue-cli 命令行工具分析

        淺談Vue-cli 命令行工具分析:Vue.js 提供一個官方命令行工具,可用于快速搭建大型單頁應用。vue-webpack-boilerplate,官方定義為: full-featured Webpack setup with hot-reload, lint-on-save, unit testing & css extraction. 目錄結(jié)構: ├
        推薦度:
        導讀淺談Vue-cli 命令行工具分析:Vue.js 提供一個官方命令行工具,可用于快速搭建大型單頁應用。vue-webpack-boilerplate,官方定義為: full-featured Webpack setup with hot-reload, lint-on-save, unit testing & css extraction. 目錄結(jié)構: ├

        Vue.js 提供一個官方命令行工具,可用于快速搭建大型單頁應用。vue-webpack-boilerplate,官方定義為:

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

        目錄結(jié)構:

        ├── 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 配置文件用來配置 devServer 的相關設定,通過配置 NODE_ENV 來確定使用何種模式(開發(fā)、生產(chǎn)、測試或其他)

        config
        |- index.js #配置文件
        |- dev.env.js #開發(fā)模式
        |- prod.env.js #生產(chǎn)模式

        index.js

        'use strict'
        const path = require('path');
        
        module.exports = {
         dev: {
        
         // 路徑
         assetsSubDirectory: 'static', // path:用來存放打包后文件的
        輸出目錄 assetsPublicPath: '/', // publicPath:指定資源文件引用的目錄 proxyTable: {}, // 代理示例: proxy: [{context: ["/auth", "/api"],target: "http://localhost:3000",}] // 開發(fā)服務器變量設置 host: 'localhost', port: 8080, autoOpenBrowser: true, // 自動打開瀏覽器devServer.open errorOverlay: true, // 瀏覽器錯誤提示 devServer.overlay notifyOnErrors: true, // 配合 friendly-errors-webpack-plugin poll: true, // 使用文件系統(tǒng)(file system)獲取文件改動的通知devServer.watchOptions // source map cssSourceMap: false, // develop 下不生成 sourceMap devtool: 'eval-source-map' // 增強調(diào)試 可能的推薦值: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

        '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 #基礎配置文件
        |- webpack.dev.conf.js #開發(fā)模式配置文件
        |- webpack.prod.conf.js #生產(chǎn)模式配置文件
        |- build.js #編譯入口

        實用代碼段 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] // 設置默認loader
         if (loader) {
         loaders.push({
         loader: loader + '-loader',
         options: Object.assign({}, loaderOptions, { // 生成 options 對象
         sourceMap: options.sourceMap
         })
         })
         }
        
         // 生產(chǎn)模式中提取css
         if (options.extract) { // 如果 options 中的 extract 為 true 配合生產(chǎn)模式
         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', 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ǒng)
        
         return (severity, errors) => {
         // 當前設定是只有出現(xiàn) error 錯誤時觸發(fā) notifier 發(fā)送通知
         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 配置文件主要根據(jù)模式定義了入口出口,以及處理 vue, babel 等的各種模塊,是最為基礎的部分。其他模式的配置文件以此為基礎通過 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, '../'), // 基礎目錄
         entry: {
         app: './src/main.js'
         },
         output: {
         path: config.build.assetsRoot, // 默認'../dist'
         filename: '[name].js',
         publicPath: process.env.NODE_ENV === 'production'
         ? config.build.assetsPublicPath // 生產(chǎn)模式publicpath
         : config.dev.assetsPublicPath // 開發(fā)模式publicpath
         },
         resolve: { // 解析確定的拓展名,方便模塊導入
         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 //可選項: 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 位數(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'
         }
        }
        
        

        開發(fā)模式配置文件 webpack.dev.conf.js

        開發(fā)模式的配置文件主要引用了 config 對于 devServer 的設定,對 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'); // 自動檢索下一個可用端口
        const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin'); // 友好提示錯誤信息
        
        const devWebpackConfig = merge(baseWebpackConfig, {
         module: {
         rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
         // 自動生成了 css, postcss, less 等規(guī)則,與自己一個個手寫一樣,默認包括了 css 和 postcss 規(guī)則
         },
        
         devtool: config.dev.devtool,// 添加元信息(meta info)增強調(diào)試
        
         // 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 優(yōu)先
         port: process.env.PORT || config.dev.port, // process.env 優(yōu)先
         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, // 文件系統(tǒng)檢測改動
         }
         },
         plugins: [
         new webpack.DefinePlugin({
         'process.env': require('../config/dev.env') // 判斷生產(chǎn)環(huán)境或開發(fā)環(huán)境
         }),
         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);
         }
         })
        })
        
        

        生產(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ù)模塊的相對路徑生成一個四位數(shù)的 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
         }),
        
         // 拷貝靜態(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 // 最小比例達到 .8 時才壓縮
         })
         )
        }
        
        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'; // 設置當前環(huán)境為生產(chǎn)環(huán)境
        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;
         // 刪除完成回調(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)錯誤.\n')); process.exit(1); } //完成 console.log(chalk.cyan(' 編譯成功.\n')) console.log(chalk.yellow( ' file:// 無用,需http(s)://.\n' )) }) })

        聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com

        文檔

        淺談Vue-cli 命令行工具分析

        淺談Vue-cli 命令行工具分析:Vue.js 提供一個官方命令行工具,可用于快速搭建大型單頁應用。vue-webpack-boilerplate,官方定義為: full-featured Webpack setup with hot-reload, lint-on-save, unit testing & css extraction. 目錄結(jié)構: ├
        推薦度:
        • 熱門焦點

        最新推薦

        猜你喜歡

        熱門推薦

        專題
        Top
        主站蜘蛛池模板: 香蕉免费一级视频在线观看| 免费看又黄又爽又猛的视频软件| yy一级毛片免费视频| 午夜免费福利在线观看| 亚洲色一区二区三区四区 | 美女被艹免费视频| 免费一级做a爰片性色毛片| 国产AV日韩A∨亚洲AV电影| 婷婷综合缴情亚洲狠狠尤物| 日韩精品免费一线在线观看 | 成人黄软件网18免费下载成人黄18免费视频 | 亚洲av无码一区二区乱子伦as| a级毛片在线免费观看| 亚洲电影中文字幕| 中文字幕人成无码免费视频| 亚洲中文字幕AV每天更新| 国产一级淫片免费播放电影| 人禽伦免费交视频播放| 亚洲成a人片在线观看无码| 久操免费在线观看| 国产精品亚洲午夜一区二区三区| 成年人在线免费观看| 人妻仑乱A级毛片免费看| 国产亚洲精品a在线无码| 亚洲精品tv久久久久| 中文字幕乱理片免费完整的| 亚洲综合自拍成人| 中文字幕在线免费看| 亚洲精品综合一二三区在线| 抽搐一进一出gif免费视频| 久久亚洲一区二区| 成人免费午夜无码视频| 春意影院午夜爽爽爽免费| 亚洲成av人影院| 最近中文字幕免费mv视频8| 久久一区二区免费播放| 亚洲成aⅴ人片在线观| 国产jizzjizz免费看jizz| 久久青草精品38国产免费| 久久精品国产亚洲av天美18| 国产aⅴ无码专区亚洲av|