天天看點

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

寫在前邊

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

代理配置

 esay 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 axios from "axios";

// axios.get("")

axios.baseURL = process.env.VUE_APP_URL;

axios.get("/api/new_article").then(res => {

  console.log(res);

});

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

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

修改 .env.development 檔案 

VUE_APP_URL = "https://www.easy-mock.com/mock/"

        // 以 “/api” 開頭的 代理到 下邊的 target 屬性 的值 中

        ws: true,

        pathRewrite: {

          // 路徑重寫

          "/api": "5ce2a7854c85c12abefbae0b/api" // 這個意思就是以api開頭的,定向到哪裡, 如果你的後邊還有路徑的話, 會自動拼接上

        }

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

記得改完配置檔案,要重新開機項目,才生效

放個自己的配置檔案

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

  /**

   * 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,

  },

  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();

      .rule("icons")

      .test(/\.svg$/)

      .include.add(resolve("src/icons"))

      .end()

      .use("svg-sprite-loader")

      .loader("svg-sprite-loader")

      .options({

        symbolId: "icon-[name]"

      })

    // set preserveWhitespace

      .rule("vue")

      .use("vue-loader")

      .loader("vue-loader")

      .tap(options => {

        options.compilerOptions.preserveWhitespace = true;

        return options;

    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");

    });