node.jstypescriptwebpackwebpack-2typescript-typings

How to fix "@types/node/index.d.ts is not a module"?


I have installed node type definitions using the following command

npm install --save-dev @types/node

After that, when I try to import the node type definitions using the following statement

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

or

import { Process } from 'node';

I get the following error

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

I am sure there is something very basic that I am missing here but I cannot figure out.

Few more things

  1. I am using Windows 8
  2. I am using Visual Studio Code

Here is how my tsconfig.json looks

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

And here is how my webpackconfig.js looks

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'
  },
};

Solution

  • Instead of using:

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

    You need to change your tsconfig.json:

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

    After doing that the process variable becomes available as a global.

    Sometimes you will need to import from a Node.js module like for example the fs module. You can do:

    import * as fs from "fs";
    

    You don't need to import fs from "node" or from "@types/node".

    You can learn more here.