无法解析 Next.js api 路由内的“fs”

noi*_*mur 5 filesystems module node.js npm next.js

我想在 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]));
  }
}

Run Code Online (Sandbox Code Playgroud)

Pie*_*tro 0

当我将 API 路由移至它时,/pages/api它就起作用了

对于其他错误:

对我来说,这个解决方案可以解决 fs 错误,但会产生其他错误:

// 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;
  }
};
Run Code Online (Sandbox Code Playgroud)