Omit the file extension, ES6 module NodeJS

删除回忆录丶 提交于 2021-01-03 07:04:25

问题


I'm trying to get a handle on Node and ES modules. Specifically how/if you can omit the file extension from the path string value of the import statement (and optionally get VSCode to autocomplete those paths).

I understand you can either gives files the .mjs extension or set "type" = "modules" in the package.json but both approaches lead to the following problems.

  1. VSCode won't autocomplete the path if the file extension is .mjs, it only sees the file if it's .js. However if it is .js the autocomplete omits the extension from the string and the import fails until I add it manually.
  2. Trying to use a library like graphql inside my own modules also fails because all the import statements between the .mjs files in the graphql module have been written omitting the extension from the string.

SO... when is not including the extension valid with ES6 module imports, and is there anyway to get this condition enabled with NodeJS?


回答1:


The node.js ES6 module implementation specifically does not do automatic file extension resolution as documented in https://nodejs.org/api/esm.html#esm_customizing_esm_specifier_resolution_algorithm :

The current specifier resolution does not support all default behavior of the CommonJS loader. One of the behavior differences is automatic resolution of file extensions and the ability to import directories that have an index file.

However this can be changed by a command line argument --experimental-specifier-resolution=[mode]

As such not giving a file extension is invalid by default but can be made valid depending on how you run node.js.

However, there are systems implemented before the ES6 spec was written that implements ES6-like import syntax such as Typescript and Babel. These systems assumed you can exclude file extensions in your imports. If you are using such a system to compile your ES6 imports to ES5 syntax you can exclude file extensions, sometimes, depending on if the version of the compiler you are using supports it.



来源:https://stackoverflow.com/questions/63459159/omit-the-file-extension-es6-module-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!