Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node can't find modules without .js extension

I have a file - test.js with these lines of code inside:

import {blabla} from "./bla";

async function dataGenerator() {
..........
}

(async() => {
  console.log('1')
  await dataGenerator()
  console.log('2')
})()

Note: Ignore the import structure. is just fictive for the question. In my file the imports are auto.

When I'm trying to run from terminal with "node test.js" it returns error:

Cannot find module 'D:\bla' imported from D:\test.js

I have added into package the line: "type": "module". Without this it returns:

Cannot use import statement outside a module

I'm using node 14.

How can I run the test.js without adding to all the imports ".js". There are functions in functions in functions and is complicated to add .js extension. Is there any npm to run it?

Thank you!

like image 630
icsul Avatar asked Oct 07 '20 10:10

icsul


1 Answers

Node.js by default does not attempt to guess the file extension when using import for ES modules. This is different from CommonJS modules with require.

In the documentation for the ES module loader you can read how files are found on disk.

The heading 'Customizing ESM specifier resolution algorithm' states:

The --experimental-specifier-resolution=[mode] flag can be used to customize the extension resolution algorithm. The default mode is explicit, which requires the full path to a module be provided to the loader. To enable the automatic extension resolution and importing from directories that include an index file use the node mode.

like image 142
RickN Avatar answered Oct 01 '22 22:10

RickN