我想在 api 路由文件中使用 fs 模块来执行一些文件系统操作,但是,我收到此错误:
Module not found: Can't resolve 'fs'
。我不仅无法在处理函数中使用 fs,而且还无法启动项目,因为 fs 错误阻止了这一点。
这就是我的文件的样子。
路径:
pages/api/getSchema.js
内容:
const fs = require("fs");
export default function handler(req, res) {
const id = req.query.id;
if(id){
const schemas = require('../../pageSchemas/index.json');
res.end(JSON.stringify(schemas[id]));
}
}
对我来说这个解决方案有效:
// next.config.js
// For Webpack 4
module.exports = {
webpack: (config, { isServer }) => {
// Fixes npm packages that depend on the `fs` module
if (!isServer) {
config.node = {
fs: 'empty'
};
}
return config;
}
};
// For Webpack 5
module.exports = {
// Remove the next line for newer versions of Next.js
webpack5: true,
webpack: (config) => {
// Disable fallback for the 'fs' module
config.resolve.fallback = { fs: false };
return config;
}
};