NodeJS(服务器):ReferenceError:需要在类型:模块时未定义 [英] NodeJS (Server): ReferenceError: require is not defined when type: module
问题描述
在 Node 13.8 上,我尝试使用导入/导出.
On Node 13.8 I'm trying to use import / export.
EG:import {ChatClient, Message, MessageParser} from './chat-client/module.js';
但是当我这样做时,我得到了
But when i do this, I get
语法错误:不能在模块外使用导入语句
所以在我的 package.json 中我设置了 "type" : "module"
但是现在当我尝试使用 const io = require('socket.io-client');代码>
So in my package.json I set "type" : "module"
but now when I try to use const io = require('socket.io-client');
我得到 ReferenceError: require is not defined
有没有办法使用导入/导出和要求?
Is there a way to use import / export AND require?
最初的错误是不是意味着我必须将我的库包装在 NPM 库中?这是一个同时使用前端和后端的库,因此使用导入/导出很重要.
The original error, does that just mean I have to wrap my library in a NPM library? It's a Library that's used both front end and backend so using import / export is important.
谢谢
推荐答案
正如文档所说:
No require, exports, module.exports, __filename, __dirname
These CommonJS variables are not available in ES modules.
https://nodejs.org/api/esm.html#esm_no_require_exports_module_exports_filename_dirname
您不能在本地同时使用两者.如果您想这样做,请使用 Babel 来转译您的代码.
You can't use both natively. If you want to do that use Babel to transpile your code.
这篇关于NodeJS(服务器):ReferenceError:需要在类型:模块时未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!