简体   繁体   中英

Preferred module syntax for node projects using typescript

I have a node project which by nature of it being node will use the CommonJS module system. What I'm confused by is that it would appear that I can use any of the following syntaxes to do the same thing:

// Traditional Node Syntax
const _ = require('lodash');
// Using the import keyword instead of a variable declaration
import _ = require('lodash');
// ES2015 module syntax
import * as _ from 'lodash';

I was thinking of just sticking with the traditional syntax but don't know if I'm missing out on anything by doing so.

One thing, however, that I do notice is that if you use the import keyword it does seem to indicate to vs-code that variable scoping should be considered to be part of the module (aka, not part of global scope) whereas it doesn't seem to be smart enough to figure that out with the traditional syntax. Notice the difference below:

使用import关键字

传统方法

In the import version you'll see that "promising-help" is highlighted because it "can't find module" which is to be expected as there is no interface or typing for it.

In the "traditional approach" however, you get a number of highlighted variables and in every case it is balking at "cannot redeclare block-scoped variable". Hmmm, this is actually misleading because in fact there is no conflict as other places where these variables have been declared are in other modules/files.

I have found, that the VS-Code's intellisense get's very unhappy with the traditional syntax so my approach at this point is to:

a) change the variable declaration into an "import" directive when converting from a JS project. this will appear more immediately familiar to nodejs developers than ES2015 syntax but as that is the future ...

b) in greenfield projects or as I start to invest more in a converted JS → TS project I have found myself moving toward the ES2015 syntax

I don't think there is any right way of doing this but above is my current thinking.

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