开发多个项目的时候,我们希望能通过指定的前缀路径去访问不同的项目。比如,通过前缀/projectA/
去访问项目A
;通过前缀/projectB/
去访问项目B
。我们应该怎么设置呢?
更改页面访问前缀
准确的来说,这一步更改的是项目资源的访问前缀,不仅仅是页面的前缀。这一步骤,我们统一设置一个变量,然后引用资源。
统一设置的这个变量,在next.config.js
文件中:
functiongetBasePath(){return'/jimmy01'}module.exports={reactStrictMode:true,basePath:getBasePath(),//添加前缀webpack(webpackConfig){webpackConfig.output.publicPath=getBasePath()webpackConfig.output.publicPath;//资源生成前缀returnwebpackConfig;},publicRuntimeConfig:{basePath:getBasePath(),//写入路径},}
然后,我们在组件中引用,比如Foot.js
公共组件:
import{useRef,useEffect}from'react';importgetConfigfrom"next/config";const{publicRuntimeConfig}=getConfig();constFoot=()=>{constrefToComponentFoot=useRef(null);useEffect(()=>{asyncfunctionanimate(){if(refToComponentFoot.current){constScrollReveal=(awaitimport("scrollreveal")).default;//动态引入ScrollReveal().reveal(refToComponentFoot.current,{delay:200});}}animate();},[])return(<footerclassName="text-sm"ref={refToComponentFoot}><divclassName="bg-gray-300"><divclassName="max-w-7xlmx-autopx-4sm:px-6py-4sm:py-6lg:py-8"><divclassName="flexflex-colsm:flex-rowjustify-betweenitems-centerjustify-startmd:space-x-10"><divclassName="flexjustify-startitems-centerlg:w-0lg:flex-1text-smtext-gray-500"><ahref="http://beian.miit.gov.cn"className="text-sm">粤ICP备***号 © ***公司</a></div><divclassName="flexspace-x-10items-centerpy-6sm:py-1"><ahref={`${publicRuntimeConfig.basePath}/legal.pdf`}className="font-mediumtext-gray-500hover:text-gray-900">法律声明 & 使用条款</a></div><divclassName="flexitems-centerjustify-endmd:flex-1lg:w-0"><ahref="https://www.***.com/en/"target="_blank"><imgclassName="h-6w-auto"src={`${publicRuntimeConfig.basePath}/footer/footer_medical.svg`}alt="medical"/></a></div></div></div></div></footer>)}exportdefaultFoot
也就是引入变量,然后访问,上面代码的访问资源地址比如:"{${publicRuntimeConfig.basePath}/footer/footer_medical.svg
}"。
项目开发完成之后,执行打包命令行npmrunbuild
生成一份构建后的压缩文件夹out
,将其更名为jimmy01
,即out->jimmy01
。我们将其上传服务器指定的路径,然后用nginx
进行代理。
这里我们更改nginx.config
中的server
字段:
server{listen80default_server;root/usr/share/nginx/fe/;//打包的文件存放的位置location/{indexindex.html;if(!-e$request_filename){rewrite^(.*)$/$1.htmlbreak;break;}}}
执行nginx-sreload
使得配置生效。通过http://domain.com/jimmy01/index.html
即可访问。
Thanksforreading.