0

created a new project in expressjs. I want to create my own class. So I created a file MyClass.js in /routes/.

class MyClass {
    constructor() {
    }
}

export default MyClass;

And in /routes/index.js i added: import MyClass from './MyClass';

And I have an error:

import MyClass from './MyClass;
^^^^^^

SyntaxError: Cannot use import statement outside a module
[...]

What I'm doing wrong?

war0den
  • 3
  • 1

2 Answers2

0

Your project is not set up properly to interpret the file that has the error as an ESM module file. It is, instead, being interpreted as a CommonJS module (where you use require(), not import) which is the nodejs default.

There are a number of ways to tell nodejs that your file is supposed to be an ESM module.

  1. You can give it a file extension of .mjs.
  2. You can add "type": "module" to your package.json file.
  3. You can use the --input-type=module command line argument when starting node.js if this file is your top level file you're executing.

See nodejs doc here on this subject.


FYI, you could just switch to the CommonJS syntax of using require() and module.exports instead of import and export, but I assume what you really want to do is to tell nodejs that you want to use ESM modules so you can use the more modern import and export syntax.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

Well first of all to export your class you suppose to use exports or module.export and to import it you suppose to use require('') not import.

Those features are only available with .mjs or if you will setup babel though soome es6 features are yet to land in

  • 1
    The OP clearly intends to use ESM `import` and `export` syntax. So, while they could convert all their code to CommonJS (using `require()` and `module.exports`), it seems more likely that the desired answer is how to get their file interpreted as an ESM module so they can use the more modern syntax `import` and `export`. – jfriend00 May 05 '21 at 22:03