最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

vue項(xiàng)目接口訪問地址設(shè)置方式

 更新時(shí)間:2023年11月09日 16:21:12   作者:瘦瘦瘦大人  
這篇文章主要介紹了vue項(xiàng)目接口訪問地址設(shè)置方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

方法一

添加.env.production和.env.development區(qū)分正式環(huán)境和測試環(huán)境。

# 開發(fā)環(huán)境配置
ENV = 'development'
 
# /開發(fā)環(huán)境
VUE_APP_BASE_API = '測試環(huán)境的接口訪問地址'
# 開發(fā)環(huán)境配置
ENV = 'production'
 
# /生產(chǎn)環(huán)境
VUE_APP_BASE_API = '開發(fā)環(huán)境的接口訪問地址'

axios請(qǐng)求的時(shí)候會(huì)拿到這兩個(gè)地址

const service = axios.create({
// axios中請(qǐng)求配置有baseURL選項(xiàng),表示請(qǐng)求URL公共部分
 
baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
 
// timeout: 5000 // request timeout
 
})

方法二

配置vue.config.js

// vue.config.js
const path = require('path');
const CompressionWebpackPlugin = require("compression-webpack-plugin"); // 開啟gzip壓縮, 按需引用
const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i; // 開啟gzip壓縮, 按需寫入
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin; // 打包分析
const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV);
const resolve = (dir) => path.join(__dirname, dir);
//用于生產(chǎn)環(huán)境去除多余的css
const PurgecssPlugin = require("purgecss-webpack-plugin");
//全局文件路徑
const glob = require("glob-all");
//壓縮代碼并去掉console
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
module.exports = {
  publicPath: process.env.NODE_ENV === 'production' ? '/site/vue-demo/' : '/', // 公共路徑
  indexPath: 'index.html' , // 相對(duì)于打包路徑index.html的路徑
  outputDir: process.env.outputDir || 'dist', // 'dist', 生產(chǎn)環(huán)境構(gòu)建文件的目錄
  assetsDir: 'static', // 相對(duì)于outputDir的靜態(tài)資源(js、css、img、fonts)目錄
  lintOnSave: false, // 是否在開發(fā)環(huán)境下通過 eslint-loader 在每次保存時(shí) lint 代碼
  runtimeCompiler: true, // 是否使用包含運(yùn)行時(shí)編譯器的 Vue 構(gòu)建版本
  productionSourceMap: !IS_PROD, // 生產(chǎn)環(huán)境的 source map
  parallel: require("os").cpus().length > 1, // 是否為 Babel 或 TypeScript 使用 thread-loader。該選項(xiàng)在系統(tǒng)的 CPU 有多于一個(gè)內(nèi)核時(shí)自動(dòng)啟用,僅作用于生產(chǎn)構(gòu)建。
  pwa: {}, // 向 PWA 插件傳遞選項(xiàng)。
  chainWebpack: config => {
Vue.prototype.$TEST_PATH;//這個(gè)地址可以用use引入,也就是用到的接口訪問地址
    config.resolve.symlinks(true); // 修復(fù)熱更新失效
    // 如果使用多頁面打包,使用vue inspect --plugins查看html是否在結(jié)果數(shù)組中
    config.plugin("html").tap(args => {
      // 修復(fù) Lazy loading routes Error
      args[0].chunksSortMode = "none";
      return args;
    });
    config.resolve.alias // 添加別名
      .set('@', resolve('src'))
      .set('@assets', resolve('src/assets'))
      .set('@components', resolve('src/components'))
      .set('@views', resolve('src/views'))
      .set('@store', resolve('src/store'));
    // 壓縮圖片
    // 需要 npm i -D image-webpack-loader
    config.module
      .rule("images")
      .use("image-webpack-loader")
      .loader("image-webpack-loader")
      .options({
        mozjpeg: { progressive: true, quality: 65 },
        optipng: { enabled: false },
        pngquant: { quality: [0.65, 0.9], speed: 4 },
        gifsicle: { interlaced: false },
        webp: { quality: 75 }
      });
    // 打包分析, 打包之后自動(dòng)生成一個(gè)名叫report.html文件(可忽視)
    if (IS_PROD) {
      config.plugin("webpack-report").use(BundleAnalyzerPlugin, [
        {
          analyzerMode: "static"
        }
      ]);
    }
  },
  configureWebpack: config => {
    // 開啟 gzip 壓縮
    // 需要 npm i -D compression-webpack-plugin
    const plugins = [];
    if (IS_PROD) {
      plugins.push(
        new CompressionWebpackPlugin({
          filename: "[path].gz[query]",
          algorithm: "gzip",
          test: productionGzipExtensions,
          threshold: 10240,
          minRatio: 0.8
        })
      );
      //啟用代碼壓縮
            plugins.push(
                new UglifyJsPlugin({
                    uglifyOptions: {
                        compress: {
                            warnings: false,
                            drop_console: true,
                            drop_debugger: false,
                            pure_funcs: ["console.log"] //移除console
                        }
                    },
                    sourceMap: false,
                    parallel: true
                })
            );
            //去掉不用的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/]
                })
            );
    }
    config.plugins = [...config.plugins, ...plugins];
  },
  css: {
    extract: IS_PROD,
    requireModuleExtension: false,// 去掉文件名中的 .module
    loaderOptions: {
        // 給 less-loader 傳遞 Less.js 相關(guān)選項(xiàng)
        less: {
          // `globalVars` 定義全局對(duì)象,可加入全局變量
          globalVars: {
            primary: '#333'
          }
        }
    }
  },
  devServer: {
      overlay: { // 讓瀏覽器 overlay 同時(shí)顯示警告和錯(cuò)誤
       warnings: true,
       errors: true
      },
      host: "localhost",
      port: 8080, // 端口號(hào)
      https: false, // https:{type:Boolean}
      open: false, //配置自動(dòng)啟動(dòng)瀏覽器
      hotOnly: true, // 熱更新
      // proxy: 'http://localhost:8080'  // 配置跨域處理,只有一個(gè)代理
      proxy: { //配置多個(gè)跨域
        "/api": {
          target: "http.....",
          changeOrigin: true,
          // ws: true,//websocket支持
          secure: false,
          pathRewrite: {
            "^/api": "/"
          }
        },
        "/api2": {
          target: "http.....",
          changeOrigin: true,
          //ws: true,//websocket支持
          secure: false,
          pathRewrite: {
            "^/api2": "/"
          }
        },
      }
    }
}

配置api目錄下index.js文件

import request from '@/utils/request'//封裝請(qǐng)求的文件
import layer from './layer' //具體接口文件
 
 
const apis = {
  install(Vue) {
    //判斷環(huán)境
    switch (location.host) {
			case 'localhost:8080':
				Vue.prototype.$TEST_PATH = '/test'//正式 在vue.config.js文件下做了跨域處理
 
				break
			case '...':
				Vue.prototype.$TEST_PATH = '/api' //測試
				break
			default:
				Vue.prototype.$TEST_PATH = '/api' //正式
				break
		}
    layer(Vue, request)
    
  },
}
export default apis

main.js引入api文件

import apis from '@/api/index.js'
Vue.use(apis)

請(qǐng)求的時(shí)候url拼上Vue.prototype.$TEST_PATH

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論

汉川市| 云阳县| 永仁县| 芮城县| 阜平县| 渝中区| 鸡西市| 潼关县| 依兰县| 兰考县| 遵义市| 游戏| 石狮市| 蓬溪县| 额尔古纳市| 石门县| 伊宁市| 卢龙县| 苏州市| 丰城市| 永嘉县| 遂昌县| 聊城市| 德兴市| 库车县| 大理市| 缙云县| 黄大仙区| 车致| 新竹县| 雅江县| 聊城市| 中西区| 湖口县| 门源| 平凉市| 自贡市| 贡山| 日土县| 五寨县| 招远市|