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

问题描述 投票:0回答:1

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

node.js npm next.js module filesystems
1个回答
0
投票

对我来说这个解决方案有效:

// 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;
  }
};
© www.soinside.com 2019 - 2024. All rights reserved.