Muhammed Aydogan
Muhammed Aydogan

Reputation: 660

How to disable file extension (".js") need for import/export in an ES6 project?

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, whenever I update the ts module, it compiles files to the other project but forgets file extensions while importing. And that means I have to manually update all extensions each time because it is a must??

So, I searched for a way to compile ts files with file extensions but found nothing. Then, I searched for disabling file extension (".js") needed for import/export in an ES6 project. I found this:

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

But he is not saying how to configure it.

Edit:

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

and when a js file has been generated that 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.

Upvotes: 13

Views: 7064

Answers (3)

phil294
phil294

Reputation: 10852

You can also solve this by setting jsconfig.json compilerOptions.moduleResolution field to "NodeNext".

Upvotes: 0

martiendt
martiendt

Reputation: 2216

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

Upvotes: 7

DINA TAKLIT
DINA TAKLIT

Reputation: 8388

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"
  },

Upvotes: 1

Related Questions