如何在 Next.js 中使用 node.js 模块? [英] How Do I use a node.js module with Next.js?

查看:233
本文介绍了如何在 Next.js 中使用 node.js 模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 next.js 中使用 express 吗?

Do I need to use express with next.js?

我正在尝试将此代码添加到 next.js 应用程序中.(来自 npm 模块示例代码:pdf2json)

Im trying to add this code into a next.js application. ( from npm module example code: pdf2json )

let fs = require('fs');
var PDFParser = require("pdf2json");
let pdfParser = new PDFParser(this,1);

pdfParser.on("pdfParser_dataError", errData => 
   console.error(errData.parserError) );
pdfParser.on("pdfParser_dataReady", pdfData => {
fs.writeFile("./sometxt.txt", pdfParser.getRawTextContent());
pdfParser.loadPDF("./page1.pdf");

推荐答案

你可以通过测试是否是服务器来有条件地要求它:

You can require it conditionally by testing if it is the server:

static async getInitialProps({isServer}){
 var fs;
 if(isServer){
  fs=require('fs');
  //and do what ever you want
 }
}

并且不要忘记告诉 webpack 不要通过像这样更改 package.json 将模块发送到客户端:

and dot not forgot to tell webpack to do not send the module to the client side by changing package.json like so:

  "browser": {
    "fs": false
  }

除非它会产生错误.

这篇关于如何在 Next.js 中使用 node.js 模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆