Next项目路径怎么添加指定的访问前缀

其他教程   发布日期:2023年08月08日   浏览次数:450

这篇文章主要讲解了“Next项目路径怎么添加指定的访问前缀”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Next项目路径怎么添加指定的访问前缀”吧!

更改项目前缀

假设我们添加的前缀为

  1. /jimmy01/

更改页面访问前缀

准确的来说,这一步更改的是项目资源的访问前缀,不仅仅是页面的前缀。这一步骤,我们统一设置一个变量,然后引用资源。

统一设置的这个变量,在

  1. next.config.js
文件中:
  1. function getBasePath() {
  2. return '/jimmy01'
  3. }
  4. module.exports = {
  5. reactStrictMode: true,
  6. basePath: getBasePath(), // 添加前缀
  7. webpack(webpackConfig) {
  8. webpackConfig.output.publicPath =
  9. getBasePath() + webpackConfig.output.publicPath; //资源生成前缀
  10. return webpackConfig;
  11. },
  12. publicRuntimeConfig: {
  13. basePath: getBasePath(), //写入路径
  14. },
  15. }

然后,我们在组件中引用,比如

  1. Foot.js
公共组件:
  1. import { useRef, useEffect } from 'react';
  2. import getConfig from "next/config";
  3. const { publicRuntimeConfig } = getConfig();
  4. const Foot = () => {
  5. const refToComponentFoot = useRef(null);
  6. useEffect(() => {
  7. async function animate() {
  8. if(refToComponentFoot.current) {
  9. const ScrollReveal = (await import("scrollreveal")).default; // 动态引入
  10. ScrollReveal().reveal(refToComponentFoot.current, { delay: 200 });
  11. }
  12. }
  13. animate();
  14. }, [])
  15. return (
  16. <footer className="text-sm" ref={ refToComponentFoot }>
  17. <div className="bg-gray-300">
  18. <div className="max-w-7xl mx-auto px-4 sm:px-6 py-4 sm:py-6 lg:py-8">
  19. <div className="flex flex-col sm:flex-row justify-between items-center justify-start md:space-x-10">
  20. <div className="flex justify-start items-center lg:w-0 lg:flex-1 text-sm text-gray-500">
  21. <a href="https://www.19jp.com">

也就是引入变量,然后访问,上面代码的访问资源地址比如:"{

  1. ${publicRuntimeConfig.basePath}/footer/footer_medical.svg
}"。

部署项目

项目开发完成之后,执行打包命令行

  1. npm run build
生成一份构建后的压缩文件夹
  1. out
,将其更名为
  1. jimmy01
,即
  1. out -> jimmy01
。我们将其上传服务器指定的路径,然后用
  1. nginx
进行代理。

这里我们更改

  1. nginx.config
中的
  1. server
字段:
  1. server {
  2. listen 80 default_server;
  3. root /usr/share/nginx/fe/; // 打包的文件存放的位置
  4. location / {
  5. index index.html;
  6. &nbsp; &nbsp; if (!-e $request_filename){
  7. rewrite ^(.*)$ /$1.html break;
  8. break;
  9. }
  10. }
  11. }

执行

  1. nginx -s reload
使得配置生效。通过
  1. http://domain.com/jimmy01/index.html
即可访问。

以上就是Next项目路径怎么添加指定的访问前缀的详细内容,更多关于Next项目路径怎么添加指定的访问前缀的资料请关注九品源码其它相关文章!