Next.js + TS 从零开始写一个前端导航页面(六、导出静态页面)

由于本次只是做一个导航页面,不太想在服务端运行 nextjs ,于是偷懒生成一个静态页面。

nextjs 自带 export 命令,可使用该命令导出静态 html 。

使用方法

package.json 新增命令

1
2
3
"scripts": {
"export": "next build && next export"
}

控制台运行 npm run export 即可将 pages 目录中的页面生成静态 html。

自定义文件名

官方配置 exportPathMap 值得拥有,该配置可以将 pages/index.tsx 重命名为任何名字。

使用方法:

根目录 next.config.js 新增配置

1
2
3
4
5
6
7
8
9
module.exports = {
exportPathMap: async function (defaultPathMap, { dev, dir, outDir, distDir, buildId }) {
return {
'/': { page: '/' },
'/about': { page: '/' },
'/p/index': { page: '/' },
}
},
}

配置以上信息后,会将 pages/index.tsx 生成三个静态页面,分别是 out/index.htmlout/about.htmlout/p/index.html

更多使用方法参考官方文档 exportPathMap

自定义打包输出目录

  • next build 默认生成的 .next 目录可以通过配置文件 distDir 修改。

根目录 next.config.js 新增配置

1
2
3
module.exports = {
distDir: 'build',
}
  • next export 默认生成的 out 目录可以命令行添加参数修改。

package.json 修改命令

1
2
3
"scripts": {
"export": "npm run build && next export -o public"
}

重新运行 npm run export html 文件会生成在 public 目录,而不是默认的 out 目录。

突发奇想:想自定义打包生成的 _next 目录,然而查了文档,也翻了源码,貌似官方没有提供这个配置,最终放弃治疗了。

清空目录

默认的 build 和 export 命令,并不会清空目录,这会导致打包生成的目录会越来越大,稍微改个文件重新打包体积都会变 2 倍,所以需要把打包后生成的目录在每次打包前清空。

根目录新增 clear.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/* eslint-disable */
const fs = require('fs');
const path = require('path');

function delDir(path) {
let files = [];
if (fs.existsSync(path)) {
files = fs.readdirSync(path);
files.forEach((file, index) => {
const curPath = path + '/' + file;
if (fs.statSync(curPath).isDirectory()) {
// 递归删除文件夹
delDir(curPath);
} else {
// 删除文件
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
}
};

delDir(path.resolve(__dirname, './.next'));
delDir(path.resolve(__dirname, './out'));

console.log('> Clear path `.next` `out`');

注意:如果自定义了 build 和 export 命令生成的目录,这儿的 .nextout 需要换成自定义的目录。

package.json 修改命令

1
2
3
"scripts": {
"export": "node clear.js && npm run build && next export"
}

这样每次运行 npm run export 都会清空 .nextout 目录。

到此,一个完整的 nextjs 页面可以跑在 nginx 服务器了。

本文由 linx(544819896@qq.com) 创作,采用 CC BY 4.0 CN协议 进行许可。 可自由转载、引用,但需署名作者且注明文章出处。本文链接为: https://blog.jijian.link/2020-06-05/next-export/

如果您觉得文章不错,可以点击文章中的广告支持一下!