[英]Run Next.js script that uses `fs` & `sharp` in development using Webpack?
I am trying to create a simple GIFPlayer
which shows GIF if someone clicks on a play button otherwise shows a PNG like:我正在尝试创建一个简单的
GIFPlayer
,如果有人点击播放按钮,它会显示 GIF,否则会显示 PNG,如:
<img className="w-full h-full" src={isPlaying ? gifPath : imgPath} alt={pic.alt} />
I only have GIF file so I create PNG file using Node.js sharp
module.我只有 GIF 文件,所以我使用 Node.js
sharp
模块创建了 PNG 文件。
const fs = require('fs')
const path = require('path')
const sharp = require('sharp')
const fg = require('fast-glob')
const ROOT_PATH = process.cwd()
const POSTS_PATH = path.join(ROOT_PATH, 'src/_posts')
function* walkSync(dir) {
const files = fs.readdirSync(dir, { withFileTypes: true })
for (let i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
yield* walkSync(path.join(dir, files[i].name))
} else {
yield path.join(dir, files[i].name)
}
}
}
const gifToPng = async () => {
try {
for (let [i, file] of [...walkSync(POSTS_PATH)].entries()) {
const extname = path.extname(file)
if (extname === '.gif') {
const dirname = path.dirname(file)
const png = path.resolve(dirname, path.basename(file).replace('.gif', '.png'))
await sharp(file).png().toFile(png)
}
}
} catch (e) {
console.error('Error thrown:', e)
}
}
gifToPng()
My next.config.js
runs this script in development like:我的
next.config.js
在开发中运行这个脚本,如:
module.exports = {
webpack: (config, options) => {
if (!options.dev && options.isServer) {
.
.
.
} else {
const originalEntry = config.entry
config.entry = async () => {
const entries = { ...(await originalEntry()) }
entries['./scripts/gif-to-png'] = './scripts/gif-to-png.js'
return entries
}
}
return config
},
}
However, its throwing error saying:但是,它的抛出错误说:
Module not found: Can't resolve 'fs'
找不到模块:无法解析“fs”
The reason I need this script in development instead of production is I need to see the PNG file in development
as well.我需要在开发中而不是生产中使用此脚本的原因是我还需要查看
development
的 PNG 文件。 Otherwise I won't be able to see it if it only runs in production .否则,如果它只在生产中运行,我将无法看到它。
How do I solve this?我该如何解决这个问题?
I found the answer here .我在这里找到了答案。
The following tells webpack
to not try and use fs
on the client build (since that will fail).以下内容告诉
webpack
不要尝试在客户端构建中使用fs
(因为这会失败)。
if (!options.isServer) {
config.resolve.fallback.fs = false
}
return config
module.exports = {
webpack: (config, options) => {
if (!options.dev && options.isServer) {
.
.
.
} else {
const originalEntry = config.entry
config.entry = async () => {
const entries = { ...(await originalEntry()) }
entries['./scripts/gif-to-png'] = './scripts/gif-to-png.js'
return entries
}
}
if (!options.isServer) {
config.resolve.fallback.fs = false
}
return config
},
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.