關於vue.config.js中配置前端代理

寫在前邊

注意開發環境的本地代理或者測試環境的代理,在部署到正式上時,一定要換成線上的IP地址,不然,數據拿不到哦

代理配置

easy mock 模擬接口地址 , 就以第一個進行說明怎麼配置和使用了, 只說代理配置部分,其它不再說明

 

新建項目(略過le... )

ip地址配置成自動切換的

首先在項目中 新建

vue.config.js    (cli配置文件)   

.env.development (配置開發和測試接口地址) 

 .env.production (配置生產環境接口地址)   

關於上邊那個配置文件參考 vue-cli 文檔,鏈接過去 的這一塊內容

先放個項目目錄

 

.env.production(將下邊的內容放進去)

## 配置測試和本地開發時的 接口地址
VUE_APP_URL = "你的開發或測試接口地址"

.env.development(將下邊的內容放進去)

## 配置 正式接口地址
VUE_APP_URL = "你的正式接口地址"

vue.config.js (代理配置參考文檔 proxy 代理 )

以下邊的接口來來測試(https://www.easy-mock.com/mock/5ce2a7854c85c12abefbae0b/api

將.env.development(將下邊的內容放進去)改掉,換成上邊的地址

## 配置測試和本地開發時的 接口地址
VUE_APP_URL = "https://www.easy-mock.com/mock/5ce2a7854c85c12abefbae0b/api"

vue.config.js中的 devServer  屬性 下 進行 配置

const port = 8589; // dev port
// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
  devServer: {
    port,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    },
    // 配置代理 (以接口 https://www.easy-mock.com/mock/5ce2a7854c85c12abefbae0b/api 說明)
    proxy: {
      "/api": {
        target: process.env.VUE_APP_URL,
        changeOrigin: true, // 是否改變域名
        ws: true
        // pathRewrite: {
        //   // 路徑重寫
        //   "/api": "" // 這個意思就是以api開頭的,定向到哪裏, 如果你的後邊還有路徑的話, 會自動拼接上
        // }
      }
    }
    // 下邊這個, 如果你是本地自己mock 的話用after這個屬性,線上環境一定要幹掉
    // after: require("./mock/mock-server.js")
  }
};

啓動測試

在main.js  中 打印 剛好拿到上邊的 地址

import Vue from "vue";
import App from "./App.vue";

Vue.config.productionTip = false;

new Vue({
  render: h => h(App)
}).$mount("#app");


console.log(process.env.VUE_APP_URL);

打印結果

測試請求(我就在 main.js 中配置了)

import Vue from "vue";
import App from "./App.vue";
import axios from "axios";
Vue.config.productionTip = false;

// axios.get("")
axios.baseURL = process.env.VUE_APP_URL;

console.log(process.env.VUE_APP_URL);

axios.get("/api/new_article").then(res => {
  console.log(res);
});

new Vue({
  render: h => h(App)
}).$mount("#app");

看一下 network (網絡), 接口已經被代理到本地

看一下上邊的那個  註釋的 那個 pathRewrite 屬性的使用 

修改 .env.development 文件 

## 配置測試和本地開發時的 接口地址
VUE_APP_URL = "https://www.easy-mock.com/mock/"

const port = 8589; // dev port
// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
  devServer: {
    port,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    },
    // 配置代理 (以接口 https://www.easy-mock.com/mock/5ce2a7854c85c12abefbae0b/api 說明)
    proxy: {
      "/api": {
        // 以 “/api” 開頭的 代理到 下邊的 target 屬性 的值 中
        target: process.env.VUE_APP_URL,
        changeOrigin: true, // 是否改變域名
        ws: true,
        pathRewrite: {
          // 路徑重寫
          "/api": "5ce2a7854c85c12abefbae0b/api" // 這個意思就是以api開頭的,定向到哪裏, 如果你的後邊還有路徑的話, 會自動拼接上
        }
      }
    }
    // 下邊這個, 如果你是本地自己mock 的話用after這個屬性,線上環境一定要幹掉
    // after: require("./mock/mock-server.js")
  }
};

這樣配置還有一個好處, 就是 你只要 改變了 接口地址, 你的代理的 地址 ,回自動幫你改變, 就不再生產和測試環境來回的手動改了, 

記得改完配置文件,要重啓項目,才生效

放個自己的配置文件

const path = require("path");

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

// If your port is set to 80,
// use administrator privileges to execute the command line.
// For example, Mac: sudo npm run
const port = 9527; // dev port

// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
  /**
   * You will need to set publicPath if you plan to deploy your site under a sub path,
   * for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
   * then publicPath should be set to "/bar/".
   * In most cases please use '/' !!!
   * Detail: https://cli.vuejs.org/config/#publicpath
   */
  publicPath: "/",
  outputDir: "dist",
  assetsDir: "static",
  lintOnSave: process.env.NODE_ENV === "development",
  productionSourceMap: false,
  devServer: {
    port,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    },
    // 配置代理 (以接口 https://www.easy-mock.com/mock/5ce2a7854c85c12abefbae0b/api 說明)
    proxy: {
      "/api": {
        // 以 “/api” 開頭的 代理到 下邊的 target 屬性 的值 中
        target: process.env.VUE_APP_URL,
        changeOrigin: true, // 是否改變域名
        ws: true,
        pathRewrite: {
          // 路徑重寫
          "/api": "5ce2a7854c85c12abefbae0b/api" // 這個意思就是以api開頭的,定向到哪裏, 如果你的後邊還有路徑的話, 會自動拼接上
        }
      }
    }
    // 下邊這個, 如果你是本地自己mock 的話用after這個屬性,線上環境一定要幹掉
    // after: require("./mock/mock-server.js")
  },
  configureWebpack: {
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    resolve: {
      // 配置別名
      alias: {
        "@": resolve("src")
      }
    }
  },
  // webpack配置覆蓋
  chainWebpack(config) {
    config.plugins.delete("preload"); // TODO: need test
    config.plugins.delete("prefetch"); // TODO: need test

    // set svg-sprite-loader
    config.module
      .rule("svg")
      .exclude.add(resolve("src/icons"))
      .end();
    config.module
      .rule("icons")
      .test(/\.svg$/)
      .include.add(resolve("src/icons"))
      .end()
      .use("svg-sprite-loader")
      .loader("svg-sprite-loader")
      .options({
        symbolId: "icon-[name]"
      })
      .end();

    // set preserveWhitespace
    config.module
      .rule("vue")
      .use("vue-loader")
      .loader("vue-loader")
      .tap(options => {
        options.compilerOptions.preserveWhitespace = true;
        return options;
      })
      .end();

    config
      // https://webpack.js.org/configuration/devtool/#development
      .when(process.env.NODE_ENV === "development", config =>
        config.devtool("cheap-source-map")
      );

    config.when(process.env.NODE_ENV !== "development", config => {
      config
        .plugin("ScriptExtHtmlWebpackPlugin")
        .after("html")
        .use("script-ext-html-webpack-plugin", [
          {
            // `runtime` must same as runtimeChunk name. default is `runtime`
            inline: /runtime\..*\.js$/
          }
        ])
        .end();
      config.optimization.splitChunks({
        chunks: "all",
        cacheGroups: {
          libs: {
            name: "chunk-libs",
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: "initial" // only package third parties that are initially dependent
          },
          elementUI: {
            name: "chunk-elementUI", // split elementUI into a single package
            priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
            test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
          },
          commons: {
            name: "chunk-commons",
            test: resolve("src/components"), // can customize your rules
            minChunks: 3, //  minimum common number
            priority: 5,
            reuseExistingChunk: true
          }
        }
      });
      config.optimization.runtimeChunk("single");
    });
  }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章