关于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");
    });
  }
};
发布了63 篇原创文章 · 获赞 100 · 访问量 31万+

猜你喜欢

转载自blog.csdn.net/qq_36407748/article/details/90679991