我有一个安装在 node_modules
中的模块,我想从中导入一个文件。
我还在我的项目所在的父目录中本地安装了此模块的版本。
出于某种原因,当我import { something } from 'my-module/myFile'
时,它实际上不是通过进入node_modules
来解决它,而是通过采取该模块的本地版本存储在我机器的其他地方,在父目录中。
为什么 TypeScript 在其构建目录之外解析模块?它怎么能在它自己的文件夹之外找到我的模块,而不仅仅是在节点模块中找到它呢?
请您参考如下方法:
从 ECMAScript 2015 开始,JavaScript 有了模块的概念。 TypeScript 也有这个概念。
模块使用模块加载器相互导入。在运行时,模块加载器负责在执行模块之前定位并执行模块的所有依赖项。 JavaScript 中使用的著名模块加载器是用于 Node.js 的 CommonJS 模块加载器和用于 Web 应用程序的 require.js。
你提到了 node_modules
所以我猜你正在使用 Node.js。 "moduleResolution": "node"
在你的 tsconfig.json 文件中。
来自 Node.js docs :
If the module identifier passed to require() is not a core module, and does not begin with '/', '../', or './', then Node.js starts at the parent directory of the current module, and adds /node_modules, and attempts to load the module from that location. Node will not append node_modules to a path already ending in node_modules.
对于 file modules :
If the exact filename is not found, then Node.js will attempt to load the required filename with the added extensions: .js, .json, and finally .node.
TypeScript overlays the TypeScript source file extensions (.ts, .tsx, and .d.ts) over the Node’s resolution logic.
确保您正确使用它。