软件开发的就业前景,如何给自家网站做关键词优化,网站开发台州,生鲜网站建设静态导出SSG
Next.js 支持静态站点生成#xff08;SSG#xff0c;Static Site Generation#xff09;#xff0c;可以在构建时预先生成所有页面的静态 HTML 文件。这种方式特别适合内容相对固定的站点#xff0c;如官网、博客、文档等#xff0c;能够提供最佳的性能和 S…静态导出SSGNext.js 支持静态站点生成SSGStatic Site Generation可以在构建时预先生成所有页面的静态 HTML 文件。这种方式特别适合内容相对固定的站点如官网、博客、文档等能够提供最佳的性能和 SEO 表现。配置静态导出需要在next.config.js文件中配置output为export表示导出静态站点。distDir表示导出目录默认为out。importtype{NextConfig}fromnext;constnextConfig:NextConfig{/* config options here */output:export,// 导出静态站点distDir:dist,// 导出目录};exportdefaultnextConfig;接着我们执行npm run build命令构建静态站点。构建完成之后我们安装http-server来启动静态站点。npminstallhttp-server -g#安装http-servercddist#进入导出目录http-server -p3000#启动静态站点启动完成之后发现点击a标签无法进行跳转是因为打完包之后的页面叫about.html,而我们的跳转链接是/about所以需要修改配置项。修改配置项需要在next.config.js文件中配置trailingSlash为true表示添加尾部斜杠生成/about/index.html而不是/about.html。importtype{NextConfig}fromnext;constnextConfig:NextConfig{/* config options here */output:export,// 导出静态站点distDir:dist,// 导出目录trailingSlash:true,// 添加尾部斜杠生成 /about/index.html 而不是 /about.html};exportdefaultnextConfig;此时重新点击a标签就可以进行跳转了。动态路由处理新建目录:src/app/posts/[id]/page.tsx如果要使用动态路由则需要使用generateStaticParams函数来生成有多少个动态路由这个函数需要返回一个数组数组中包含所有动态路由的参数例如{ id: 1 }表示对应id为1的详情页。exportasyncfunctiongenerateStaticParams(){//支持调用接口请求详情id列表 const res await fetch(https://api.example.com/posts)return[{id:1},//返回对应的详情id{id:2},]}exportdefaultasyncfunctionPost({params}:{params:Promise{id:string}}){const{id}awaitparamsreturn(divh1Post{id}/h1/div)}图片优化如果使用Image组件优化图片在开发模式会进行报错⚠️ 警告get-img-props.ts 442 Uncaught Error: Image Optimization using the default loader is not compatible with{ output: export }.可能的解决方案移除{ output: export }并运行 next start 以启用包含图片优化 API 的服务器模式。在next.config.js中配置{ images: { unoptimized: true } }来禁用图片优化 API。使用自定义loader实现了解更多https://nextjs.org/docs/messages/export-image-apiimportImagefromnext/imageimporttestfrom/public/1.pngexportdefaultfunctionAbout(){return(divh1About/h1Image loadingeagersrc{test}altlogowidth{250*3}height{131*3}//div)}我们使用自定义loader来实现图片优化,要求我们通过一个图床托管图片。路过图床 是一个免费的图床我们可以使用它来托管图片。importtype{NextConfig}fromnext;constnextConfig:NextConfig{/* config options here */output:export,// 导出静态站点distDir:dist,// 导出目录trailingSlash:true,// 添加尾部斜杠生成 /about/index.html 而不是 /about.htmlimages:{loader:custom,// 自定义loaderloaderFile:./image-loader.ts,// 自定义loader文件},};exportdefaultnextConfig;根目录/image-loader.tsexportdefaultfunctionimageLoader({src,width,quality}:{src:string,width:number,quality:number}){returnhttps://s41.ax1x.com${src}}src/app/about/page.tsximportImagefromnext/imageexportdefaultfunctionAbout(){return(divh1About/h1Image loadingeagersrc/2025/12/29/pZYbW7t.jpgaltlogowidth{250*3}height{131*3}//div)}注意事项以下功能在SSG中不支持请勿使用Dynamic Routes with dynamicParams: true动态路由没有使用generateStaticParams()路由处理器依赖于RequestCookiesRewrites重写Redirects重定向Headers头Proxy代理Incremental Static Regeneration增量静态再生Image Optimization with the default loader默认加载器的图像优化Draft Mode草稿模式Server Actions服务器操作Intercepting Routes拦截路由