1. 程式人生 > 其它 >vue 配置【詳解】 vue.config.js ( 含 webpack 配置 )

vue 配置【詳解】 vue.config.js ( 含 webpack 配置 )

技術標籤:Vue

目錄

常用配置

完整配置


使用vue-cli 3.x 腳手架建立的 vue 專案不再有 build資料夾,若需要進行相關配置,需在專案目錄下新建檔案vue.config.js

常用配置

// 後端伺服器地址
let url = 'http://localhost:8888'
module.exports = {
    publicPath: './',  // 【必要】靜態檔案使用相對路徑
    outputDir: "./dist", //打包後的資料夾名字及路徑
    devServer: {  // 開發環境跨域情況的代理配置
        proxy: {
            // 【必要】訪問自己搭建的後端伺服器
            '/': {
                //要訪問的域名(後端伺服器地址)
                target: url,
                //開啟代理:在本地會建立一個虛擬服務端,然後傳送請求的資料,並同時接收請求的資料,這樣客戶端和服務端進行資料的互動就不會有跨域問題
                changOrigin: true,
                ws: true,        // 是否啟用websockets
                secure: false,   // 使用的是http協議則設定為false,https協議則設定為true
                pathRewrite: {   //  介面地址改寫
                    '^/': '/'
                }
            },
            // 【範例】訪問百度地圖的API
            // vue檔案中使用方法  this.$http.get("/baiduMapAPI/place/v2/search"
            // 最終實際訪問的介面為  http://api.map.baidu.com/place/v2/search
            '/baiduMapAPI': {
                target: 'http://api.map.baidu.com',
                changOrigin: true,
                ws: true,
                secure: false,
                pathRewrite: {
                    '^/baiduMapAPI': ''
                }
            },
        }
    }
}

完整配置

const path = require("path");
const resolve = dir => path.join(__dirname, dir);
//用於生產環境去除多餘的css
const PurgecssPlugin = require("purgecss-webpack-plugin");
//全域性檔案路徑
const glob = require("glob-all");
//壓縮程式碼並去掉console
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
//程式碼打包zip
const CompressionWebpackPlugin = require("compression-webpack-plugin");
const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i;
module.exports = {
  // 廢棄baseUrl  一般運維會配置好的
  publicPath: process.env.NODE_ENV === "production" ? "/configtest/" : "/",
  //打包的輸出目錄
  outputDir: "dist/configtest",
  //儲存時是否校驗
  lintOnSave: true,
  //如果檔案等設定
  pages: {
    index: {
      entry: "src/main.js",
      template: "public/index.html",
      filename: "index.html"
    }
  },
  //靜態資源打包路徑
  assetsDir: "static",
  //預設false 可以加快打包
  productionSourceMap: false,
  //打包後的啟動檔案
  indexPath: "congfigtest.html",
  //打包檔案是否使用hash
  filenameHashing: true,
  runtimeCompiler: false,
  transpileDependencies: [],
  //打包的css路徑及命名
  css: {
    modules: false,
    //vue 檔案中修改css 不生效 註釋掉  extract:true
    extract: {
      filename: "style/[name].[hash:8].css",
      chunkFilename: "style/[name].[hash:8].css"
    },
    sourceMap: false,
    loaderOptions: {
      css: {},
      less: {
        // 向全域性less樣式傳入共享的全域性變數
        // data: `@import "~assets/less/variables.less";$src: "${process.env.VUE_APP_SRC}";`
      },
      // postcss 設定
      postcss: {
        plugins: [
          require("postcss-px-to-viewport")({
            viewportWidth: 750, // 視窗的寬度,對應的是我們設計稿的寬度,一般是750
            viewportHeight: 1334, // 視窗的高度,根據750裝置的寬度來指定,一般指定1334,也可以不配置
            unitPrecision: 3, // 指定`px`轉換為視窗單位值的小數位數(很多時候無法整除)
            viewportUnit: "vw", // 指定需要轉換成的視窗單位,建議使用vw
            selectorBlackList: [".ignore", ".hairlines"], // 指定不轉換為視窗單位的類,可以自定義,可以無限新增,建議定義一至兩個通用的類名
            minPixelValue: 1, // 小於或等於`1px`不轉換為視窗單位,你也可以設定為你想要的值
            mediaQuery: false // 允許在媒體查詢中轉換`px`
          })
        ]
      }
    }
  },
  //webpack 鏈式配置   預設已經配置好了  node_moudles/@vue
  chainWebpack: config => {
    // 修復HMR
    config.resolve.symlinks(true);
    // 修復Lazy loading routes  按需載入的問題,如果沒有配置按需載入不需要寫,會報錯
    // config.plugin("html").tap(args => {
    //   args[0].chunksSortMode = "none";
    //   return args;
    // });
    //新增別名
    config.resolve.alias
      .set("@", resolve("src"))
      .set("assets", resolve("src/assets"))
      .set("components", resolve("src/components"))
      .set("layout", resolve("src/layout"))
      .set("base", resolve("src/base"))
      .set("static", resolve("src/static"));
    // 壓縮圖片
    config.module
      .rule("images")
      .use("image-webpack-loader")
      .loader("image-webpack-loader")
      .options({
        mozjpeg: { progressive: true, quality: 65 },
        optipng: { enabled: false },
        pngquant: { quality: "65-90", speed: 4 },
        gifsicle: { interlaced: false },
        webp: { quality: 75 }
      });
  },
  //webpack 配置
  configureWebpack: config => {
    const plugins = [];
    //去掉不用的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/]
      })
    );
    //啟用程式碼壓縮
    plugins.push(
      new UglifyJsPlugin({
        uglifyOptions: {
          compress: {
            warnings: false,
            drop_console: true,
            drop_debugger: false,
            pure_funcs: ["console.log"] //移除console
          }
        },
        sourceMap: false,
        parallel: true
      })
    ),
      //程式碼壓縮打包
      plugins.push(
        new CompressionWebpackPlugin({
          filename: "[path].gz[query]",
          algorithm: "gzip",
          test: productionGzipExtensions,
          threshold: 10240,
          minRatio: 0.8
        })
      );
    config.plugins = [...config.plugins, ...plugins];
  },
  parallel: require("os").cpus().length > 1,
  pluginOptions: {},
  pwa: {},
  //設定代理
  devServer: {
    port: 8080,
    host: "0.0.0.0",
    https: false,
    open: true,
    openPage: "about",
    hot: true,
    disableHostCheck: true,
    proxy: {
      "/api": {
        target: "https://cdn.awenliang.cn",
        ws: true,
        changeOrigin: true
      },
      "/foo": {
        target: "https://cdn.awenliang.cn",
        ws: true,
        changeOrigin: true
      }
    }
  }
};