如何在Next.js中运行一个脚本构建时间(附实例)

188 阅读1分钟

我想看看把我的博客(基于Hugo)移到Next.js上是否是一个好的举措(不是),我发现了一个问题。

我不得不改变我的每张图片的路径,因为Hugo允许一篇文章与markdown文件在同一个文件夹里,而Next.js则不允许。

但我并不想打乱我的工作流程。我可以把我的图片和markdown文件放在同一个文件夹里,这真是太好了。这对编写和维护来说非常容易。

所以我有这样的计划:在构建时,我将浏览所有的帖子,收集图片,并在/public/images ,为每个帖子创建一个文件夹。

我必须在markdown中改变每个图片的路径,这是最简单的事情。

然后,我不得不运行一个后建命令,创建一个postbuild.mjs 文件,其工作是通过我的content/posts 文件夹,并将每个图片复制到public/images

import fs from 'fs'
import path from 'path'
import fsExtra from 'fs-extra'

const source = './content/posts'
const destination = './public/images'

const posts = fs.readdirSync(source)

fsExtra.emptyDirSync(destination)

fs.mkdir(destination, () => {
  posts.map((slug) => {
    if (slug === '.DS_Store') return

    fs.mkdir(`${destination}/${slug}`, () => {
      fs.readdirSync(`${source}/${slug}`)
        .filter((item) =>
          ['.png', '.jpg', '.jpeg', '.gif'].includes(path.extname(item))
        )
        .map((item) => {
          fs.copyFile(
            `${source}/${slug}/${item}`,
            `${destination}/${slug}/${item.replace(/ /g, '-')}`,
            () => {
              console.log(`${destination}/${slug}/${item}`)
            }
          )
        })
    })
  })
})

然后在你的package.json 文件中添加一个postbuild 条目scripts

{
  ...
  "scripts": {
    "build": "next build",
    "postbuild": "node ./postbuild.mjs",
    "dev": "next dev",
    "start": "next start",
    ...
  }
}

使用同样的技术,你可以创建一个prebuild 条目,在构建之前运行。

顺便说一下,这不是Next.js独有的,它是npm的一个功能。见docs.npmjs.com/cli/v6/usin…