【问题标题】:Wrap Typescript definition file in module automatically自动将 Typescript 定义文件包装在模块中
【发布时间】:2016-06-10 14:43:16
【问题描述】:

我很可能在这里遗漏了一些 tsconfig 选项。

我做的很简单:

我正在创建一个 npm 模块,例如:

export class HelloWorld {
    constructor(public greeting: string){}
}

我的 tsconfig 是:

{
  "compilerOptions": {
    "target": "ES5",
    "module": "commonjs",
    "removeComments": true,
    "noImplicitAny": false,
    "preserveConstEnums": true,
    "declaration": true,
    "suppressImplicitAnyIndexErrors": true,
    "outDir": "../js"
  },
  "filesGlob": [
    "./**/*.ts",
    "!./node_modules/**/*.ts"
  ]
}

当我的声明被自动创建时,它看起来像这样:

export declare class HelloWorld {
    greeting: string;
    constructor(greeting: string);
}

但是在其他项目中实际安装 npm 包时,这并不好用。当我导入我必须使用的包时:

import hello = require("hello-world/js/index");

(例如)

我发现当我将声明文件包装在模块declare module "hello-world" {...}中时,我可以根据import hello = require("hello-world");的需要导入它

手动包装生成的定义文件不是一个选项,因为它一直在重写自己,是否有任何选项可以从 package.json 获取包的名称并自动将定义包装在该模块中?

【问题讨论】:

  • 你试过'export default class HelloWorld'吗?
  • @baryo 是的,没有任何区别
  • 你能发布你的 package.json 吗?
  • 看看这篇文章,它解释了打字稿在哪里寻找打字等:ivanz.com/2016/06/07/…

标签: node.js typescript npm


【解决方案1】:

确保您在package.json 中指定了typings 属性...

{
    "name": "hello-world",
    "typings": "hello-world.d.ts",
    ...etc...
}

...或将您的定义文件更改为index.d.ts

那么在安装完这些改动的包后,编译器就可以在你写的时候解析了:

import hello = require("hello-world");

More details

【讨论】:

  • import {HelloWorld} from 'hello-world'; new HelloWorld("greeting here"); 而不是 require ?
  • @IvanZlatev 我一直使用 es6 模块,但我只使用了 require,因为他们也使用了它。老实说,我对 require 工作原理的确切记忆正在慢慢消失 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-20
  • 2021-10-27
  • 2012-11-29
  • 1970-01-01
  • 2017-11-05
  • 1970-01-01
  • 2019-01-29
相关资源
最近更新 更多