最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

vue3中vue.config.js配置及注釋詳解

 更新時間:2022年08月04日 10:16:19   作者:執(zhí)著1111  
在Vue 3.0中,與2.0版本相比有一定的差別,最明顯的就是缺少了build、config文件夾,下面這篇文章主要給大家介紹了關(guān)于vue3中vue.config.js配置及注釋的相關(guān)資料,需要的朋友可以參考下

報錯

asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).
This can impact web performance.
entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance.
Entrypoints:

打包時提示文件過大,配置解決方案,如下

直接設(shè)置文件的壓縮率就可以

//核心代碼
configureWebpack: (config) => {
    if (process.env.NODE_ENV === 'production') {// 為生產(chǎn)環(huán)境修改配置...
      config.mode = 'production';
      config["performance"] = {//打包文件大小配置
        "maxEntrypointSize": 10000000,
        "maxAssetSize": 30000000
      }
    }
  }

上代碼:

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  assetsDir: 'static',
  productionSourceMap: false,
  chainWebpack: config => {
    config.resolve.alias
      .set('@', resolve('src'))
      .set('assets', resolve('src/assets'))
      .set('components', resolve('src/components'))
  },
  configureWebpack: (config) => {
    if (process.env.NODE_ENV === 'production') {// 為生產(chǎn)環(huán)境修改配置...
      config.mode = 'production';
      config["performance"] = {//打包文件大小配置
        "maxEntrypointSize": 10000000,
        "maxAssetSize": 30000000
      }
    }
  }
})

還有一種方法就是對其進(jìn)行壓縮

安裝依賴

npm install compression-webpack-plugin --save-dev

在vue.config.js中引用

const CompressionWebpackPlugin = require("compression-webpack-plugin");

配置壓縮文件

datav-vue:一個基于Vuejs3的數(shù)據(jù)可視化(DataV)項目下載地址:點(diǎn)擊這里

const productionGzipExtensions = ["js", 'css'];

配置對超過大小文件進(jìn)行壓縮

new CompressionWebpackPlugin({
      filename: "[path][base].gz",
      algorithm: "gzip",
      test: new RegExp("\\.(" + productionGzipExtensions.join("|") + ")$"), //匹配文件名
      threshold: 10240, //對10K以上的數(shù)據(jù)進(jìn)行壓縮
      minRatio: 0.8,
      deleteOriginalAssets: false //是否刪除源文件
    })

下面時完整代碼

const { defineConfig } = require('@vue/cli-service')
const path = require('path');
const CompressionWebpackPlugin = require("compression-webpack-plugin"); // 開啟gzip壓縮, 按需引用
const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i; // 開啟gzip壓縮, 按需寫入
const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV);
const resolve = (dir) => path.join(__dirname, dir);
const TerserPlugin = require('terser-webpack-plugin')//去除多余的console.log

module.exports = defineConfig({
  transpileDependencies: true,
  assetsDir: 'static',
  productionSourceMap: false,
  integrity: true,
  crossorigin: undefined,
  chainWebpack: config => {
    config.resolve.symlinks(true); // 修復(fù)熱更新失效
    // 如果使用多頁面打包,使用vue inspect --plugins查看html是否在結(jié)果數(shù)組中
    config.plugin("html").tap(args => {
      // 修復(fù) Lazy loading routes Error
      args[0].chunksSortMode = "none";
      return args;
    });
    config.resolve.alias // 添加別名
      .set('@', resolve('src'))
      .set('@assets', resolve('src/assets'))
      .set('@components', resolve('src/components'))
      .set('@views', resolve('src/views'))
      .set('@store', resolve('src/store'));
    // 壓縮圖片
    // 需要 npm i -D image-webpack-loader
    config.module
      .rule("images")
      .use("image-webpack-loader")
      .loader("image-webpack-loader")
      .options({
        mozjpeg: { progressive: true, quality: 65 },
        optipng: { enabled: false },
        pngquant: { quality: [0.65, 0.9], speed: 4 },
        gifsicle: { interlaced: false },
        webp: { quality: 75 }
      });
  },
  configureWebpack: (config) => {
    // 開啟 gzip 壓縮
    // 需要 npm i -D compression-webpack-plugin
    const plugins = [];
    if (IS_PROD) {
      plugins.push(
        new CompressionWebpackPlugin({
          filename: '[path].gz[query]',
          algorithm: 'gzip',
          test: productionGzipExtensions,
          threshold: 10240,//大于10k的進(jìn)行壓縮
          minRatio: 0.8,
        })
      );
      plugins.push(
        //打包環(huán)境去掉console.log等
        new TerserPlugin({
          terserOptions: {
            ecma: undefined,
            warnings: false,
            parse: {},
            compress: {
              drop_console: true,
              drop_debugger: false,
              pure_funcs: ['console.log'], // 移除console
            },
          },
        }),
      );
    }
    config.plugins = [...config.plugins, ...plugins];
  },
})

我這個是最方法,大家可以復(fù)制到自己的項目中直接使用,我的是5.x的webpack,同類型版本的可以直接使用 需要nginx也配合使用壓縮,開啟全局http壓縮

gzip  off;
gzip_static on;
gzip_min_length 10k;
gzip_buffers 4 16k;
gzip_comp_level 6;
gzip_types application/javascript application/css text/css text/javascript;
gzip_disable "MSIE [1-6]\.";
gzip_vary on;

這種方法是最優(yōu)方法真正的考慮性能用的,上面的第一種方法只是讓其不提示了而已,不會去考慮性能問題

vue.config.js配置詳解注釋

// vue.config.js
const path = require('path');
const CompressionWebpackPlugin = require("compression-webpack-plugin"); // 開啟gzip壓縮, 按需引用
const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i; // 開啟gzip壓縮, 按需寫入
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin; // 打包分析
const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV);
const resolve = (dir) => path.join(__dirname, dir);
//用于生產(chǎn)環(huán)境去除多余的css
const PurgecssPlugin = require("purgecss-webpack-plugin");
//全局文件路徑
const glob = require("glob-all");
//壓縮代碼并去掉console
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
module.exports = {
  publicPath: process.env.NODE_ENV === 'production' ? '/site/vue-demo/' : '/', // 公共路徑
  indexPath: 'index.html' , // 相對于打包路徑index.html的路徑
  outputDir: process.env.outputDir || 'dist', // 'dist', 生產(chǎn)環(huán)境構(gòu)建文件的目錄
  assetsDir: 'static', // 相對于outputDir的靜態(tài)資源(js、css、img、fonts)目錄
  lintOnSave: false, // 是否在開發(fā)環(huán)境下通過 eslint-loader 在每次保存時 lint 代碼
  runtimeCompiler: true, // 是否使用包含運(yùn)行時編譯器的 Vue 構(gòu)建版本
  productionSourceMap: !IS_PROD, // 生產(chǎn)環(huán)境的 source map
  parallel: require("os").cpus().length > 1, // 是否為 Babel 或 TypeScript 使用 thread-loader。該選項在系統(tǒng)的 CPU 有多于一個內(nèi)核時自動啟用,僅作用于生產(chǎn)構(gòu)建。
  pwa: {}, // 向 PWA 插件傳遞選項。
  chainWebpack: config => {
    config.resolve.symlinks(true); // 修復(fù)熱更新失效
    // 如果使用多頁面打包,使用vue inspect --plugins查看html是否在結(jié)果數(shù)組中
    config.plugin("html").tap(args => {
      // 修復(fù) Lazy loading routes Error
      args[0].chunksSortMode = "none";
      return args;
    });
    config.resolve.alias // 添加別名
      .set('@', resolve('src'))
      .set('@assets', resolve('src/assets'))
      .set('@components', resolve('src/components'))
      .set('@views', resolve('src/views'))
      .set('@store', resolve('src/store'));
    // 壓縮圖片
    // 需要 npm i -D image-webpack-loader
    config.module
      .rule("images")
      .use("image-webpack-loader")
      .loader("image-webpack-loader")
      .options({
        mozjpeg: { progressive: true, quality: 65 },
        optipng: { enabled: false },
        pngquant: { quality: [0.65, 0.9], speed: 4 },
        gifsicle: { interlaced: false },
        webp: { quality: 75 }
      });
    // 打包分析, 打包之后自動生成一個名叫report.html文件(可忽視)
    if (IS_PROD) {
      config.plugin("webpack-report").use(BundleAnalyzerPlugin, [
        {
          analyzerMode: "static"
        }
      ]);
    }
  },
  configureWebpack: config => {
    // 開啟 gzip 壓縮
    // 需要 npm i -D compression-webpack-plugin
    const plugins = [];
    if (IS_PROD) {
      plugins.push(
        new CompressionWebpackPlugin({
          filename: "[path].gz[query]",
          algorithm: "gzip",
          test: productionGzipExtensions,
          threshold: 10240,
          minRatio: 0.8
        })
      );
      //啟用代碼壓縮
            plugins.push(
                new UglifyJsPlugin({
                    uglifyOptions: {
                        compress: {
                            warnings: false,
                            drop_console: true,
                            drop_debugger: false,
                            pure_funcs: ["console.log"] //移除console
                        }
                    },
                    sourceMap: false,
                    parallel: true
                })
            );
            //去掉不用的css 多余的css
            plugins.push(
                new PurgecssPlugin({
                    paths: glob.sync([path.join(__dirname, "./**/*.vue")]),
                    extractors: [
                        {
                            extractor: class Extractor {
                                static extract(content) {
                                    const validSection = content.replace(
                                        /<style([\s\S]*?)<\/style>+/gim,
                                        ""
                                    );
                                    return validSection.match(/[A-Za-z0-9-_:/]+/g) || [];
                                }
                            },
                            extensions: ["html", "vue"]
                        }
                    ],
                    whitelist: ["html", "body"],
                    whitelistPatterns: [/el-.*/],
                    whitelistPatternsChildren: [/^token/, /^pre/, /^code/]
                })
            );
    }
    config.plugins = [...config.plugins, ...plugins];
  },
  css: {
    extract: IS_PROD,
    requireModuleExtension: false,// 去掉文件名中的 .module
    loaderOptions: {
        // 給 less-loader 傳遞 Less.js 相關(guān)選項
        less: {
          // `globalVars` 定義全局對象,可加入全局變量
          globalVars: {
            primary: '#333'
          }
        }
    }
  },
  devServer: {
      overlay: { // 讓瀏覽器 overlay 同時顯示警告和錯誤
       warnings: true,
       errors: true
      },
      host: "localhost",
      port: 8080, // 端口號
      https: false, // https:{type:Boolean}
      open: false, //配置自動啟動瀏覽器
      hotOnly: true, // 熱更新
      // proxy: 'http://localhost:8080'  // 配置跨域處理,只有一個代理
      proxy: { //配置多個跨域
        "/api": {
          target: "http://172.11.11.11:7071",
          changeOrigin: true,
          // ws: true,//websocket支持
          secure: false,
          pathRewrite: {
            "^/api": "/"
          }
        },
        "/api2": {
          target: "http://172.12.12.12:2018",
          changeOrigin: true,
          //ws: true,//websocket支持
          secure: false,
          pathRewrite: {
            "^/api2": "/"
          }
        },
      }
    }
}

總結(jié)

到此這篇關(guān)于vue3中vue.config.js配置及注釋詳解的文章就介紹到這了,更多相關(guān)vue3 vue.config.js配置詳解內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 淺談Vue入門需掌握的知識

    淺談Vue入門需掌握的知識

    這篇文章主要介紹了淺談Vue入門需掌握的知識,感興趣的同學(xué)參考下
    2021-04-04
  • 在vue中安裝使用vux的教程詳解

    在vue中安裝使用vux的教程詳解

    這篇文章主要介紹了在vue中安裝使用vux的教程,本文給大家記錄了vuex的安裝使用過程,非常不錯,具有一定的參考借鑒價值 ,需要的朋友可以參考下
    2018-09-09
  • Vue3實(shí)現(xiàn)檢測密碼強(qiáng)度值功能

    Vue3實(shí)現(xiàn)檢測密碼強(qiáng)度值功能

    本文將演示如何使用Vue?3實(shí)現(xiàn)一個簡單的密碼強(qiáng)度檢測功能,通過實(shí)時反饋,幫助用戶創(chuàng)建更安全的密碼,從而提升整體系統(tǒng)的安全性,需要的朋友可以參考下
    2024-06-06
  • vue cli實(shí)現(xiàn)項目登陸頁面流程詳解

    vue cli實(shí)現(xiàn)項目登陸頁面流程詳解

    CLI是一個全局安裝的npm包,提供了終端里的vue命令。它可以通過vue create快速搭建一個新項目,或者直接通過vue serve構(gòu)建新想法的原型。你也可以通過vue ui通過一套圖形化界面管理你的所有項目
    2022-10-10
  • Vue中使用import進(jìn)行路由懶加載的原理分析

    Vue中使用import進(jìn)行路由懶加載的原理分析

    這篇文章主要介紹了Vue中使用import進(jìn)行路由懶加載的原理分析。具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-04-04
  • vue父組件傳值子組件報錯Avoid?mutating?a?prop?directly解決

    vue父組件傳值子組件報錯Avoid?mutating?a?prop?directly解決

    這篇文章主要為大家介紹了vue父組件傳值子組件報錯Avoid?mutating?a?prop?directly解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-09-09
  • vue require.context全局注冊組件的具體實(shí)現(xiàn)

    vue require.context全局注冊組件的具體實(shí)現(xiàn)

    本文主要介紹了vue require.context全局注冊組件,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-05-05
  • vue的安裝及element組件的安裝方法

    vue的安裝及element組件的安裝方法

    下面小編就為大家分享一篇vue的安裝及element組件的安裝,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-03-03
  • vue實(shí)現(xiàn)登錄時的圖片驗(yàn)證碼

    vue實(shí)現(xiàn)登錄時的圖片驗(yàn)證碼

    這篇文章主要為大家詳細(xì)介紹了vue實(shí)現(xiàn)登錄時的圖片驗(yàn)證碼,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-04-04
  • Vue數(shù)據(jù)驅(qū)動模擬實(shí)現(xiàn)1

    Vue數(shù)據(jù)驅(qū)動模擬實(shí)現(xiàn)1

    這篇文章主要介紹了Vue數(shù)據(jù)驅(qū)動模擬實(shí)現(xiàn)的相關(guān)資料,允許采用簡潔的模板語法聲明式的將數(shù)據(jù)渲染進(jìn)DOM,且數(shù)據(jù)與DOM綁定在一起,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-01-01

最新評論

安泽县| 荔波县| 西乌珠穆沁旗| 措勤县| 安多县| 长寿区| 城步| 娱乐| 陕西省| 光山县| 彰武县| 阿拉善右旗| 广汉市| 平邑县| 阳城县| 丰宁| 庐江县| 永丰县| 榆树市| 敖汉旗| 静乐县| 榆林市| 宁明县| 高要市| 泾源县| 海安县| 印江| 建水县| 淄博市| 裕民县| 兴仁县| 通河县| 青铜峡市| 三明市| 横山县| 财经| 天长市| 江油市| 墨竹工卡县| 筠连县| 舟曲县|