I'm writing an app using Node.js. Specifically, I'm using Node v10.3.0. This app is located in a directory located at ./my-module-console/index.js
. This app have a package.json file located at ./my-module-console/package.json
. This app references a class defined in ./my-module/items/
. It should be noted that my-module
represents its own package. That package is defined in ./my-module/package.json
. The code in index.js looks like this:
'use strict';
import { Item } from '../my-module/items/item.js';
async function entry() {
let item = await Item.FindById(1);
console.log(item);
}
entry();
When I attempt to run this, I get the following error:
import { Item } from '../my-module/items/item.js';
^
SyntaxError: Unexpected token {
What is wrong with my import statement? It looks correct to me. Am I misunderstanding something?
item.js
class Item {
constructor() {}
async static FindById(id) {
console.log('finding item by id: ' + id);
}
};
module.exports = Item;
Thanks!
As mentioned by @jsur ES Modules are still experimental. But if you want to use them you have to add --experimental-modules
. If you still want to use ES Modules then you have to rename .js to .mjs and also the item.js, it is commonJS style now, has to be changed to ES Modules + small other fix. And also you don't really have to use 'use strict', it is strict by default. So finally it should look like this:
index.mjs
import { Item } from '../my-module/items/item';
async function entry() {
let item = await Item.FindById(1);
console.log(item);
}
entry();
item.mjs
export class Item {
constructor() {}
static async FindById(id) {
console.log('finding item by id: ' + id);
}
}
So now just do node --experimental-modules index.mjs
and you're good to go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With