Next项目路径添加指定的访问前缀方法详解
作者:Jimmy
这篇文章主要介绍了Next项目路径添加指定的访问前缀方法详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
前言
开发多个项目的时候,我们希望能通过指定的前缀路径去访问不同的项目。比如,通过前缀 /projectA/ 去访问项目 A;通过前缀 /projectB/ 去访问项目 B。我们应该怎么设置呢?
上一篇文章中,我们讲解了 SPA 项目中 Angular 项目路径添加指定的访问前缀,本文我们讲讲 MPA 项目对路径前缀的更改。
这里使用的框架是 Next.js,版本号为 11.1.2
更改项目前缀
假设我们添加的前缀为 /jimmy01/
更改页面访问前缀
准确的来说,这一步更改的是项目资源的访问前缀,不仅仅是页面的前缀。这一步骤,我们统一设置一个变量,然后引用资源。
统一设置的这个变量,在 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; // 动态引入
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 href="http://beian.miit.gov.cn" 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}"。
部署项目
项目开发完成之后,执行打包命令行 npm run build 生成一份构建后的压缩文件夹 out,将其更名为 jimmy01,即 out -> jimmy01。我们将其上传服务器指定的路径,然后用 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;
}
}
}
执行 nginx -s reload 使得配置生效。通过 http://domain.com/jimmy01/index.html 即可访问。
Thanks for reading.
以上就是Next项目路径添加指定的访问前缀方法详解的详细内容,更多关于Next 路径指定访问前缀的资料请关注脚本之家其它相关文章!
