简体   繁体   中英

How to correctly use import in Node JS

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.

What do I need to change to get import to work?


I have 3 simple files in the same directory.

  1. package.json
  2. main.js
  3. Utility.js

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM