Reputation: 49
I added "type": "module" to package.json. I was under the impression no translation between ES6 and CommonJS was necessary with the newer versions of node to use import, in this case v16.0.0.
I have 3 simple files in the same directory.
package.json
{
"name": "node_template",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"type": "module"
}
Utility.js
'use strict';
class Utility {
constructor() {
}
}
export { Utility };
main.js
"use strict";
(async ()=>{
import { Utility } from './Utility.js';
var utility = new Utility();
console.log( "Main" );
})();
When I run "node main.js" I get the following error:
node -v
v16.0.0
node main.js
main.js:4
import { Utility } from './Utility.js';
^
SyntaxError: Unexpected token '{'
←[90m at Loader.moduleStrategy (node:internal/modules/esm/translators:147:18)
←[39m
←[90m at async link (node:internal/modules/esm/module_job:64:21)←[39m
Upvotes: 4
Views: 1768
Reputation: 66
main.js
(async () => {
let { Utility } = await import('./Utility.js');
let utility = new Utility();
console.log('main');
})();
Note: The import statement you used, should only be used at top-level of the module. But you can dynamically or conditionally import module by using dynamic import - import(). See the links below for more detail.
Links:
https://v8.dev/features/dynamic-import
https://flaviocopes.com/javascript-dynamic-imports/
Upvotes: 1