vue項(xiàng)目接口訪問地址設(shè)置方式
更新時間:2023年11月09日 16:21:12 作者:瘦瘦瘦大人
這篇文章主要介紹了vue項(xiàng)目接口訪問地址設(shè)置方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
方法一
添加.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請求的時候會拿到這兩個地址
const service = axios.create({
// axios中請求配置有baseURL選項(xià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' , // 相對于打包路徑index.html的路徑
outputDir: process.env.outputDir || 'dist', // 'dist', 生產(chǎn)環(huán)境構(gòu)建文件的目錄
assetsDir: 'static', // 相對于outputDir的靜態(tài)資源(js、css、img、fonts)目錄
lintOnSave: false, // 是否在開發(fā)環(huán)境下通過 eslint-loader 在每次保存時 lint 代碼
runtimeCompiler: true, // 是否使用包含運(yùn)行時編譯器的 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 有多于一個內(nèi)核時自動啟用,僅作用于生產(chǎn)構(gòu)建。
pwa: {}, // 向 PWA 插件傳遞選項(xiàng)。
chainWebpack: config => {
Vue.prototype.$TEST_PATH;//這個地址可以用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 }
});
// 打包分析, 打包之后自動生成一個名叫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` 定義全局對象,可加入全局變量
globalVars: {
primary: '#333'
}
}
}
},
devServer: {
overlay: { // 讓瀏覽器 overlay 同時顯示警告和錯誤
warnings: true,
errors: true
},
host: "localhost",
port: 8080, // 端口號
https: false, // https:{type:Boolean}
open: false, //配置自動啟動瀏覽器
hotOnly: true, // 熱更新
// proxy: 'http://localhost:8080' // 配置跨域處理,只有一個代理
proxy: { //配置多個跨域
"/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'//封裝請求的文件
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 apismain.js引入api文件
import apis from '@/api/index.js' Vue.use(apis)
請求的時候url拼上Vue.prototype.$TEST_PATH
總結(jié)
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue3實(shí)現(xiàn)轉(zhuǎn)盤抽獎效果的示例詳解
這篇文章主要為大家詳細(xì)介紹了如何通過Vue3實(shí)現(xiàn)簡單的轉(zhuǎn)盤抽獎效果,文中的示例代碼講解詳細(xì),具有一定的借鑒價值,感興趣的可以了解一下2023-10-10
Vue Element前端應(yīng)用開發(fā)之echarts圖表
在我們做應(yīng)用系統(tǒng)的時候,往往都會涉及圖表的展示,綜合的圖表展示能夠給客戶帶來視覺的享受和數(shù)據(jù)直觀體驗(yàn),同時也是增強(qiáng)客戶認(rèn)同感的舉措之一2021-05-05
vuejs2.0運(yùn)用原生js實(shí)現(xiàn)簡單拖拽元素功能
這篇文章主要為大家詳細(xì)介紹了vuejs2.0運(yùn)用原生js實(shí)現(xiàn)簡單拖拽元素功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-12-12
詳解Vue返回值動態(tài)生成表單及提交數(shù)據(jù)的辦法
這篇文章主要為大家介紹了Vue返回值動態(tài)生成表單及提交數(shù)據(jù),具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2021-12-12

