8

I have a ts module. I'm compiling this module to another project's specific folder by using "outDir" of tsconfig.json and the command "tsc -w". So, every time when I update the ts module it compiles files to the other project but forgetting file extensions while importing. And that means I have to manually update all extensions each time because it is a must in ES6.

I searched if there's a way to compile ts files with file extensions but found nothing. And I searched to disable file extension (".js") need for import/export in an ES6 project. Then I found this:

...configure your server to ignore the extension...

But he is not saying how to configure.

Edit:

I am running my project with nodemon src/index.js

and when a js file generated which has an import without extension this is the error nodemon gave:

[nodemon] restarting due to changes...
[nodemon] starting `node src/index.js`
internal/process/esm_loader.js:74
    internalBinding('errors').triggerUncaughtException(
                              ^

Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\Users\......\trendyol' imported from C:\Users\.......\index.js
    at finalizeResolution (internal/modules/esm/resolve.js:276:11)
    at moduleResolve (internal/modules/esm/resolve.js:699:10)
    at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:810:11)
    at Loader.resolve (internal/modules/esm/loader.js:86:40)
    at Loader.getModuleJob (internal/modules/esm/loader.js:230:28)
    at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:56:40)
    at link (internal/modules/esm/module_job.js:55:36) {
  code: 'ERR_MODULE_NOT_FOUND'
}
[nodemon] app crashed - waiting for file changes before starting...

But when I add extensions ("js"), it works as expected.

Muhammed Aydogan
  • 570
  • 1
  • 4
  • 22
  • 2
    *"because it is a must in ES6"* That's not true as such. ES6 itself doesn't care about the structure of module identifiers at all. The *environment* that processes the module identifiers might care. So where/how are those JavaScript files executed? – Felix Kling Apr 21 '21 at 12:40
  • I found a solution [here](https://stackoverflow.com/a/66414052/10908886) – Muhammed Aydogan Apr 21 '21 at 15:23

2 Answers2

1

Because relative import paths need full extensions in ESM (we have to write import "./foo.js" instead of import "./foo")

So you have 2 different solution :

  1. add .js extension to your import file

or

  1. use --experimental-specifier-resolution=node to ignore extension on runtime
Kristian
  • 2,456
  • 8
  • 23
  • 23
martiendt
  • 1,909
  • 1
  • 17
  • 27
1

You can do this by adding --experimental-modules --es-module-specifier-resolution=node to you start script in package.json:

  "scripts": {
    "start": "nodemon --experimental-modules --es-module-specifier-resolution=node index.js"
  },
DINA TAKLIT
  • 7,074
  • 10
  • 69
  • 74