简体   繁体   中英

How do I convert my existing node application to typescript?

I have a functioning node project. It was written using javascript. The app is pretty simple (mostly, it was just hosting a static folder). Some of the web pages it was hosting are successfully using typescript for client javascript. Now I'm trying to convert my node to typescript (I'm using Visual Studio Code as an IDE), and I'm having a lot of weird errors, and it's hard to find out what I'm doing wrong as the error messages aren't coming up in any good searches.

I downloaded the .d.ts files from definitely typed and put it into a typescript folder, then I renamed my index.js file to index.ts , and added a reference to it in the tasks.json file so that it would compile the new typescript file. Then I added the typescript stuff to the top of my index.js

///<reference path='ts/express.d.ts' />

import * as express from "express";
var app = express();
var path = require('path');

When I did that, I got these error messages

C:/src/www/ts/node.d.ts (128,29): Expected ';'
C:/src/www/ts/mime.d.ts (17,12): Expected identifer after 'import'
C:/src/www/ts/mime.d.ts (27,12): Expected identifer after 'import'
C:/src/www/ts/mime.d.ts (3,8): Expected identifer after 'import'

Is there something wrong with the .d.ts files?

My typescript isn't as good as the guys who wrote the d.ts files, I'm sure, and this line looks right:

isBuffer(obj: any): obj is Buffer;

but is the line that generates the Expected ';' error, but I don't really trust that, because the other three error messages occur in mime.d.ts which doesn't contain the word import .

So, I thought I'd start smaller, and created a separate JS file. It just contains:

import * as express from "express";

And that generates the same error message.

C:/src/www/simple.ts (1,8): Expected identifer after 'import'

What am I doing wrong?

-- Updates --

This is my tsconfig

{ "compilerOptions": {
    "target": "es5",
    "module": "amd",
    "sourceMap": true    
}}

You're using typescript 0.8.3, which is very outdated. It may be (or not) the solution, but it's a good start to keep it up to date. I'm using Atom as my IDE, so I've installed typescript with npm, which always resolve to latest version. Don't know about VS Code.

About your .tsconfig , ideally you should be using typings to manage .d.ts files. It will download and organize all typings definition in a single directory with a single entry point (called main.d.ts ). This file and all others .ts files are then listed on files property of your .tsconfig file, so the compiler knows which files to use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM