如何在 Typescript 中导入具有 Typescript 主文件的 npm 模块? [英] How to import an npm module that has a Typescript main file in Typescript?
问题描述
我不知道导入 Typescript npm 模块的正确方法是什么.
I can't figure out what's the proper way of importing a Typescript npm module.
这是我尝试这样做的方法:
Here's how I'm trying to do it:
模块 package.json
{
"name": "my-module",
"main": "src/myModule.ts"
}
模块 src/myModule.ts
export module MyModule {
// Code inside
}
使用 npm 模块的代码
import { MyModule } from 'my-module'; // Doesn't work
import { MyModule } = require('my-module'); // Doesn't work.
该模块作为依赖项安装在package.json中,例如我可以做到
The module is installed as a dependency in the package.json, and for example I can do
import { MyModule } from '../node_modules/my-module/src/myModule.ts';
但显然这不是很好.我想要的是一种只导入主模块文件中的任何导出的方法,但这似乎不可能.
But obviously this isn't great. What I want is a way to just import any exports that are in the main module file, but it doesn't seem possible.
推荐答案
package.json 中的 'main' 仅对打包工具如 webpack 或 angular-cli 的构建工具有用.用于根据用户需求选择不同的bundle:ES6、ES5、UMD...
The 'main' in package.json is useful only to packaging tools like webpack or the build tool of angular-cli. It is used to select different bundles according to the user's needs: ES6, ES5, UMD...
TypeScript 忽略了这一点.你需要指定你想要的文件,就像你引用你自己的项目一样:
TypeScript ignores that. You need to specify the file you want, exactly as if you were refering to your own project:
import { MyModule } from 'my-module/src/myModule';
Angular 等其他库所做的是创建一个桶,一个通常称为index.ts"或index.d.ts"的文件,用于导入和导出库中的所有类型.
What other libraries like Angular do is to create a barrel, a file usually called 'index.ts' or 'index.d.ts', that imports and exports all types in the library.
这样做的好处是,如果你在 my-module 的根目录下创建一个 index.d.ts 文件:
The advantage of this is that, if you create a index.d.ts file in the root of my-module:
export { MyModule } from './src/myModule';
// other exports
你可以简单地这样做:
import {MyModule} from 'my-module'
作为打字稿,从文件夹导入时,自动使用 index.ts
或 index.d.ts
文件.
As typescript, when importing from a folder, automatically uses a index.ts
or index.d.ts
file.
这篇关于如何在 Typescript 中导入具有 Typescript 主文件的 npm 模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!