省略文件扩展名,ES6模块NodeJS [英] Omit the file extension, ES6 module NodeJS

查看:49
本文介绍了省略文件扩展名,ES6模块NodeJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解Node和ES模块.具体来说,如何/是否可以从import语句的路径字符串值中省略文件扩展名(并且可以选择使VSCode自动完成这些路径).

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).

我了解您可以为文件提供 .mjs 扩展名,也可以设置"type"= json.中的模块" ,但是两种方法都会导致以下问题.

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.

    如果文件扩展名为 .mjs
  1. VSCode不会自动完成路径,只有 .js 时,VSCode才会看到该文件.但是,如果它是 .js ,则自动完成功能会忽略字符串中的扩展名,并且导入会失败,直到我手动添加它为止.
  2. 尝试在我自己的模块中使用像 graphql 这样的库也失败了,因为graphql模块中 .mjs 文件之间的所有导入语句均已写成省略了扩展名从字符串中获取.
  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 ...何时不包括对ES6模块导入有效的扩展,是否有通过NodeJS启用此条件的方法?

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

推荐答案

当前的说明符分辨率不支持CommonJS加载程序的所有默认行为.行为差异之一是文件扩展名的自动解析以及导入具有索引文件的目录的能力.

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.

但是,可以通过命令行参数-experimental-specifier-resolution = [mode]

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

因此,不提供文件扩展名默认为无效,但可以根据运行node.js的方式使其有效.

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

但是,在编写ES6规范之前已经实现了一些系统,这些系统实现了类似ES6的 import 语法,例如Typescript和Babel.这些系统假定您可以在导入中排除文件扩展名.如果您使用这样的系统将ES6 import 编译为ES5语法,则有时可以排除文件扩展名,具体取决于您使用的编译器版本是否支持它.

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.

这篇关于省略文件扩展名,ES6模块NodeJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆