问题
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
- I am using Windows 8
- 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'
},
};
回答1:
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.
回答2:
It's because inside the node typing file any module has declared with name node.
If you use
import { Process } from 'node';
TypeScript will try too find a node module or node namespace
Here you can load the complete file using
import 'node';
In your case you want to get only Process from NodeJS namespace :
import 'NodeJS';
Aftert that you just need to call it like this :
class toto implements NodeJS.Process{
}
EDIT :
If you use TypeScript >= 2.0 you should not need to add import in your file, only if you want to "optimize import"
来源:https://stackoverflow.com/questions/44416902/how-to-fix-types-node-index-d-ts-is-not-a-module