Reputation: 3351
I am trying to write a package for node in TypeScript that uses standard node libraries, for example fs
, path
, stream
, http
, and so on.
When I try to import libraries in a .ts file, VS Code marks the corresponding line with an error:
[ts] Cannot find module 'fs'
.
This happens no matter how I try to import the library:
import * as fs from 'fs'; // [ts] Cannot find module 'fs'
import fs = require('fs'); // [ts] Cannot find module 'fs'
const fs = require('fs'); // [ts] Cannot find name 'require'
I (should) have the correct definitions installed with typings install --save --ambient node
.
When I compile to JavaScript (using gulp
and gulp-typescript
, not tsc
), the compliation works and the syntax highlighting shows no errors until I type in 1 character again:
How can I correctly define the node libraries for TypeScript?
I use VS Code for code highlighting and autocompletion, gulp
& gulp-typescript
to compile and typings
for the typescript library declarations.
The project's directory structure:
├─ build/
│ └─ (output files)
├─ src/
│ └─ myfile.ts
├─ typings/
│ ├─ browser/
│ │ └─ ambient/
│ │ └─ node/
│ │ └─ index.d.ts
│ ├─ main/
│ │ └─ ambient/
│ │ └─ node/
│ │ └─ index.d.ts
│ ├─ browser.d.ts
│ └─ main.d.ts
├─ gulpfile.js
├─ package.json
├─ tsconfig.json
└─ typings.json
My tsconfig.json
:
{
"compileOnSave": false,
"compilerOptions": {
"declaration": true,
"module": "system",
"moduleResolution": "node",
"noEmitOnError": true,
"noImplicitAny": true,
"target": "es5"
},
"exclude": [
"node_modules",
"typings/browser",
"typings/browser.d.ts"
]
}
My typings.json
:
{
"ambientDependencies": {
"node": "registry:dt/node#4.0.0+20160412142033"
}
}
And my gulp task:
gulp.task('build-typescript', () => {
const gulpts = require('gulp-typescript');
const tsProject = gulpts.createProject('tsconfig.json', {
typescript: require('typescript'),
outFile: 'mylibrary.js',
noLib: true
});
let tsstream = (
gulp.src([
'node_modules/typescript/lib/lib.es6.d.ts',
'typings/main.d.ts',
'src/sharpscript.ts'])
.pipe(sourcemaps.init())
.pipe(gulpts(tsProject))
);
return require('merge2')(
tsstream.dts.pipe(gulp.dest('build')),
tsstream.js
.pipe(sourcemaps.write('.', { includeContent: true }))
.pipe(gulp.dest('build'))
);
});
In case anyone has experienced the same problem, I am thankful for any insights.
Upvotes: 8
Views: 3269
Reputation: 3907
the installation of type declarations with 'typings install ...' is obsolete since a few months. The new way is to install it directly via npm and the @types namespace. to install the node type declarations just use npm install @types/node --save-dev
.
Upvotes: 3