Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS (Server): ReferenceError: require is not defined when type: module

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

SyntaxError: Cannot use import statement outside a module

So in my package.json I set "type" : "module" but now when I try to use const io = require('socket.io-client');

I get ReferenceError: require is not defined

Is there a way to use import / export AND require?

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.

Thanks

like image 817
TheBritishAreComing Avatar asked Feb 24 '20 13:02

TheBritishAreComing


1 Answers

As the documentation says:

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

You can't use both natively. If you want to do that use Babel to transpile your code.

like image 61
Johnny Zabala Avatar answered Oct 24 '22 14:10

Johnny Zabala