5

I have a react app set up with webpack, and would like to also have a script that runs in node to write stuff into output file, such as:

script.mjs

import fs from 'fs';
import {SomeClass} from './index.js';

const outputFile= fs.createWriteStream(__dirname + '/output.png');

// Writes into output file

and have the following script command in package.json:

"scripts": {
  ...
  "runFile": "node --experimental-modules test/script.mjs",
  ...
}

Whenever I run npm run runFile it complains with:

import {SomeClass} from './index.js';
        ^^^^^^^^^
SyntaxError: The requested module './index.js' does not provide an export named 'SomeClass'

even though it exists in that file:

./index.js

export SomeClass from './SomeClass';

I even used node -r esm test/script.js to run in node, but it keeps complaining about ES6 exports all the time. Could anybody point me to how to run a js file that has ES6 stuff with node command?

NODE v10

sfasfasd
  • 97
  • 1
  • 5

1 Answers1

0

There is a small inconsistency in your export/import statements.

Oh, and you are exporting from an entirely different file. Is there are reason you need to do so?

You may export an containing your class

export { someClass 

Then you can import it with the present import statement.

More direct would be to export from your ./someClass file with a default export

export default someClass

then import it without destructuring the object:

import some class from './someClass';

The latter would fit well with the file name and is a style expected by most.

Note that when you run old node versions you need some extra CLI flags to run modules. With present node (^13) it is enough to set type: module. See Hao Wu's answer.

gschenk
  • 827
  • 9
  • 17