Next項目路徑添加指定的訪問前綴方法詳解
前言
開發(fā)多個項目的時候,我們希望能通過指定的前綴路徑去訪問不同的項目。比如,通過前綴 /projectA/ 去訪問項目 A;通過前綴 /projectB/ 去訪問項目 B。我們應(yīng)該怎么設(shè)置呢?
上一篇文章中,我們講解了 SPA 項目中 Angular 項目路徑添加指定的訪問前綴,本文我們講講 MPA 項目對路徑前綴的更改。
這里使用的框架是 Next.js,版本號為 11.1.2
更改項目前綴
假設(shè)我們添加的前綴為 /jimmy01/
更改頁面訪問前綴
準確的來說,這一步更改的是項目資源的訪問前綴,不僅僅是頁面的前綴。這一步驟,我們統(tǒng)一設(shè)置一個變量,然后引用資源。
統(tǒng)一設(shè)置的這個變量,在 next.config.js 文件中:
function getBasePath() {
return '/jimmy01'
}
module.exports = {
reactStrictMode: true,
basePath: getBasePath(), // 添加前綴
webpack(webpackConfig) {
webpackConfig.output.publicPath =
getBasePath() + webpackConfig.output.publicPath; //資源生成前綴
return webpackConfig;
},
publicRuntimeConfig: {
basePath: getBasePath(), //寫入路徑
},
}
然后,我們在組件中引用,比如 Foot.js 公共組件:
import { useRef, useEffect } from 'react';
import getConfig from "next/config";
const { publicRuntimeConfig } = getConfig();
const Foot = () => {
const refToComponentFoot = useRef(null);
useEffect(() => {
async function animate() {
if(refToComponentFoot.current) {
const ScrollReveal = (await import("scrollreveal")).default; // 動態(tài)引入
ScrollReveal().reveal(refToComponentFoot.current, { delay: 200 });
}
}
animate();
}, [])
return (
<footer className="text-sm" ref={ refToComponentFoot }>
<div className="bg-gray-300">
<div className="max-w-7xl mx-auto px-4 sm:px-6 py-4 sm:py-6 lg:py-8">
<div className="flex flex-col sm:flex-row justify-between items-center justify-start md:space-x-10">
<div className="flex justify-start items-center lg:w-0 lg:flex-1 text-sm text-gray-500">
<a rel="external nofollow" className="text-sm">粵ICP備***號 © ***公司</a>
</div>
<div className="flex space-x-10 items-center py-6 sm:py-1">
<a href={`${publicRuntimeConfig.basePath}/legal.pdf`} className="font-medium text-gray-500 hover:text-gray-900">法律聲明 & 使用條款</a>
</div>
<div className="flex items-center justify-end md:flex-1 lg:w-0">
<a
href="https://www.***.com/en/" rel="external nofollow"
target="_blank"
>
<img
className="h-6 w-auto"
src={`${publicRuntimeConfig.basePath}/footer/footer_medical.svg`}
alt="medical"
/>
</a>
</div>
</div>
</div>
</div>
</footer>
)
}
export default Foot
也就是引入變量,然后訪問,上面代碼的訪問資源地址比如:"{${publicRuntimeConfig.basePath}/footer/footer_medical.svg}"。
部署項目
項目開發(fā)完成之后,執(zhí)行打包命令行 npm run build 生成一份構(gòu)建后的壓縮文件夾 out,將其更名為 jimmy01,即 out -> jimmy01。我們將其上傳服務(wù)器指定的路徑,然后用 nginx 進行代理。
這里我們更改 nginx.config 中的 server 字段:
server {
listen 80 default_server;
root /usr/share/nginx/fe/; // 打包的文件存放的位置
location / {
index index.html;
if (!-e $request_filename){
rewrite ^(.*)$ /$1.html break;
break;
}
}
}
執(zhí)行 nginx -s reload 使得配置生效。通過 http://domain.com/jimmy01/index.html 即可訪問。
Thanks for reading.
以上就是Next項目路徑添加指定的訪問前綴方法詳解的詳細內(nèi)容,更多關(guān)于Next 路徑指定訪問前綴的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Javascript將數(shù)值轉(zhuǎn)換為金額格式(分隔千分位和自動增加小數(shù)點)
這篇文章主要介紹Javascript將數(shù)值轉(zhuǎn)換為金額格式的方法,通俗易懂,需要的朋友可以參考下。2016-06-06

