약 프런트 엔드 프록시 구성을 vue.config.js

전면에 서면

공식에 배포 할 때 참고 개발 환경 또는 로컬 프록시 에이전트의 테스트 환경, 라인이 IP 주소로 대체해야합니다, 그렇지 않으면 데이터가 오 얻을 수 없다

프록시 구성

쉬운 모의 아날로그 인터페이스 주소, 먼저 어떻게 구성 및 사용에 설명하고, 해당 프록시 구성의 일부, 다른 설명이 없습니다

 

새 프로젝트 (스킵 르 ...)

IP 주소가 자동으로 스위치에 구성

새 프로젝트의 첫 번째에서

vue.config.js CLI (프로파일)   

.env.development (개발 및 테스트 구성 인터페이스 어드레스) 

 .env.production (생산 환경 구성 인터페이스 어드레스)   

해당 구성 파일 참조의 위에  VUE-CLI  문서, 과거에이 콘텐츠를 링크

프로젝트 디렉토리를 넣으려면

 

.env.production (그들에 아래의 내용)

인터페이스 주소 구성 테스트와 ## 지역 개발
VUE_APP_URL = "개발 또는 테스트 인터페이스 주소."

.env.development (그들에 아래의 내용)

## 인터페이스의 공식 주소 구성
= "인터페이스의 공식 주소를."VUE_APP_URL을

vue.config.js (프록시 구성 참조 문서  프록시 에이전트  )

측 인터페이스하기 시험 ( https://www.easy-mock.com/mock/5ce2a7854c85c12abefbae0b/api )

.env.development (그들에 아래의 내용)을 없애, 상단 주소를 대체

인터페이스 주소 구성 테스트와 ## 지역 개발
VUE_APP_URL = "https://www.easy-mock.com/mock/5ce2a7854c85c12abefbae0b/api"

devServer의 특성에 따라 구성된 Vue.config.js

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

인쇄 결과

테스트 요청 (I 구성에 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");

네트워크 (네트워크) 봐, 인터페이스는 로컬 에이전트에있다

코멘트의 상단에 봐 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 · 전망 310 000 +

추천

출처blog.csdn.net/qq_36407748/article/details/90679991