【问题标题】:How to fix "@types/node/index.d.ts is not a module"?如何修复“@types/node/index.d.ts 不是模块”?
【发布时间】:2017-11-09 01:23:28
【问题描述】:

我已经使用以下命令安装了节点类型定义

npm install --save-dev @types/node

之后,当我尝试使用以下语句导入节点类型定义时

import { Process } from '@types/node';

import { Process } from 'node';

我收到以下错误

[ts] File '<root_path>/node_modules/@types/node/index.d.ts' is not a module.

我确信这里缺少一些非常基本的东西,但我无法弄清楚。

还有一些事情

  1. 我使用的是 Windows 8
  2. 我正在使用 Visual Studio Code

这是我的tsconfig.json 的样子

{
  "compilerOptions": {
    "target": "es2015",
    "module": "commonjs",
    "outDir": "lib",
    "typeRoots": [
        "node_modules/@typings"
    ]
  },
  "exclude": [
    "node_modules"
  ]
}

这就是我的webpackconfig.js 的样子

var path = require('path');

module.exports = {  
  entry: './ts/handler.ts',
  target: 'node',
  module: {
    loaders: [
      { test: /\.ts(x?)$/, loader: 'ts-loader' },      
      { test: /\.json$/, loader: 'json-loader' }
    ]
  },
  resolve: {
    extensions: ['.ts', '.js', '.tsx', '.jsx']
  },
  output: {
    libraryTarget: 'commonjs',
    path: path.join(__dirname, '.webpack'),
    filename: 'handler.js'
  },
};

【问题讨论】:

  • 您不需要从@types/node 导入。您只需要从“节点”导入。您还需要将typeRoots 中的[ "node_modules/@types" ] 更改为tsconfig.json
  • @embarq 仅从 node 导入后出现相同错误
  • @embarq 在更改typeRoots 后仍然出现同样的错误。

标签: node.js typescript webpack webpack-2 typescript-typings


【解决方案1】:

而不是使用:

import { Process } from '@types/node';

您需要更改您的tsconfig.json

{
  "compilerOptions": {
    ...
    "typeRoots": ["node_modules/@types"]
  }
}

完成此操作后,流程变量可作为全局变量使用。

有时您需要从 Node.js 模块导入,例如 fs 模块。你可以这样做:

import * as fs from "fs";

您不需要从“node”或“@types/node”导入fs

您可以了解更多here

【讨论】:

  • 我已经进行了更改,现在我将对其进行测试。只是一个快速 - 所以我不能使用节点类型定义中定义的Process 接口?
  • 我觉得你可以用NodeJS.Process
  • 您不应该使用 import 来键入和更改 tsconfig 中的任何内容,TypeScript >= 2.0。
【解决方案2】:

这是因为在节点类型文件中,任何模块都声明了名称为 node

如果你使用

import { Process } from 'node';

TypeScript 也会尝试查找 节点模块节点命名空间

在这里您可以使用

加载完整的文件
import 'node';

在您的情况下,您只想从 NodeJS 命名空间获取 Process :

import 'NodeJS';

你只需要这样称呼它:

class toto implements NodeJS.Process{

}

编辑:

如果你使用 TypeScript >= 2.0,你应该不需要在你的文件中添加导入,只有当你想“优化导入”时

【讨论】:

    【解决方案3】:

    我刚刚在 tsconfig 文件中更改了

    "typeRoots": ["./src/interfaces/index.d.ts"] 
    

    这个到

    "typeRoots": ["node_modules/@types"]
    

    及其工作原理。

    之后我遇到了猫鼬库的问题。

    Module 'mongoose' has no exported member 'QueryFindOneAndUpdateOptions'
    

    然后我安装了猫鼬版本库

    npm install mongoose@5.8.1 
    

    它现在正在工作。

    【讨论】:

      猜你喜欢
      • 2018-12-07
      • 2020-01-18
      • 2022-12-16
      • 2019-04-18
      • 2017-02-07
      • 2018-12-05
      • 2018-11-10
      • 2017-04-05
      • 2019-08-14
      相关资源
      最近更新 更多