【问题标题】:how to use node_modules/@types/* and my own types together?如何一起使用 node_modules/@types/* 和我自己的类型?
【发布时间】:2017-12-01 08:10:43
【问题描述】:

我将typescriptwebpack2react 一起使用。

webpackProviderPlugin 提供了一些全局变量。

我在我的entry 文件中使用它,如下所示:

console.log(process.env.NODE_ENV);
console.log(__PROD__);

但是typescript编译器给我一个错误:

Error:(14, 13) TS2304:Cannot find name '__PROD__'.

我创建自己的类型文件:

./types/index.d.ts:

declare const __PROD__: boolean;

我的tsconfig.json:

{
  "version": "2.3.4",
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/",
    "allowJs": true,
    "sourceMap": true,
    "allowSyntheticDefaultImports": false,
    "experimentalDecorators": true,

    "lib": [
      "es5",
      "es2015",
      "DOM",
      "ScriptHost"
    ],
    "typeRoots": [
      "./node_modules/@types"
    ],
    "target": "es5",
    "module": "commonjs",
    "jsx": "react",

    "pretty": true,

    "strictNullChecks": true,
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noUnusedLocals": false,
    "noUnusedParameters": false
  },
  "include": [
    "./src/**/*"    
  ],
  "exclude": [
    "dist",
    "node_modules",
    "**/*.spec.ts",
    "__test__"
  ]
}

你看,我已经将node_modules/@types 用于react 和其他库。

但是如何添加自己的类型定义?

【问题讨论】:

    标签: typescript typescript2.0


    【解决方案1】:

    从您的配置看来,您应该能够将./types/index.d.ts 添加到您的include。如果您已按照评论中所述将其移至 ./src/types/index.d.ts,请对该路径执行相同操作。

    说明

    基本上,你现在只想告诉 TypeScript 一些全局的。您已经创建了一个带有 .d.ts 文件的 types 文件夹,其中包含有关 __PROD__ 全局(即 ./types/index.d.ts)的所有信息

    所以你只需要让 TypeScript 读取它以前没有做的那个文件。只需将该文件添加到您的 include 列表中,一切都会正常。

    【讨论】:

    • 我将我的baseUrl 更改为./src 并将我的types 目录移动到src,它可以工作。但是,你能解释一下吗?意思是*.d.ts文件的内容可以被所有.ts文件访问吗?它是全球性的?
    • 好的。谢谢。如果我有很多*.d.ts 文件,我想将其他d.ts 收集到index.d.ts 并只想将./types/index.d.ts 添加到我的include 列表中,我该怎么做?
    • 从您现有的设置中不清楚,这取决于 .d.ts 文件的编写方式。 This StackOverflow question/answer 可能会有所帮助,但如果没有更多详细信息,我将无法正确回答。
    • 谢谢!答案很好!
    猜你喜欢
    • 2018-11-04
    • 1970-01-01
    • 2017-02-06
    • 2022-08-02
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 2011-01-29
    • 1970-01-01
    相关资源
    最近更新 更多