简体   繁体   English

Node 找不到没有 .js 扩展名的模块

[英]Node can't find modules without .js extension

I have a file, test.js with these lines of code inside:我有一个文件test.js ,里面有这些代码行:

import {blabla} from "./bla";

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

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

Note: Ignore the import structure.注意:忽略导入结构。 It 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:当我尝试使用node test.js从终端运行时,它返回错误:

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

I have added into package.json the line: "type": "module" .我在package.json中添加了这一行: "type": "module" Without this it returns:没有这个,它会返回:

Cannot use import statement outside a module

I'm using node v14 .我正在使用节点v14 How can I run the test.js without adding to all the imports ".js" .如何在不添加所有导入".js"的情况下运行test.js There are functions in functions in functions and is complicated to add .js extension.函数中有函数中的函数,添加.js扩展名很复杂。 Is there any npm to run it?有任何 npm 来运行它吗?

Node.js by default does not attempt to guess the file extension when using import for ES modules.默认情况下,Node.js 在对 ES 模块使用import时不会尝试猜测文件扩展名。 This is different from CommonJS modules with require .这与带有require的 CommonJS 模块不同。

In the documentation for the ES module loader you can read how files are found on disk.ES 模块加载器的文档中,您可以阅读如何在磁盘上找到文件。

The heading 'Customizing ESM specifier resolution algorithm' states:标题“自定义 ESM 说明符解析算法”指出:

The --experimental-specifier-resolution=[mode] flag can be used to customize the extension resolution algorithm. --experimental-specifier-resolution=[mode]标志可用于自定义扩展解析算法。 The default mode is explicit , which requires the full path to a module be provided to the loader.默认模式是explicit的,它需要将模块的完整路径提供给加载器。 To enable the automatic extension resolution and importing from directories that include an index file use the node mode.要启用自动扩展解析并从包含索引文件的目录导入,请使用node模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM