关于node.js:用typescript导入Node js中的类

importing class in Node js with typescript

我将在nodejs中导入类,并在app.ts

中使用它

1
2
3
4
5
6
7
8
9
var nano = require("nano");
import { EnvConfig } from './envConfig.service';
let config = new EnvConfig();
const dbCredentials: any = config.appEnv.getServiceCreds('dataservices');
export const nanodb = nano({
  url: dbCredentials.url,
});
export const nanodbCockpitLight = nanodb.use('data');
console.log(dbCredentials);

当我尝试编译时,出现此错误。

1
2
3
import { EnvConfig } from './envConfig.service';
       ^
SyntaxError: Unexpected token {

我已经创建了tsconfig文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
 "compilerOptions": {
   "module":"commonjs",
   "declaration": false,
   "noImplicitAny": false,
   "removeComments": true,
   "noLib": false,
   "allowSyntheticDefaultImports": true,
   "emitDecoratorMetadata": true,
   "experimentalDecorators": true,
   "target":"es6",
   "sourceMap": true,
   "allowJs": true,
   "outDir":"./dist",
    //"baseUrl":"src" // Attention !! nécessite l'utilisation d'un loader de module node pour fonctionner sur node
  },
 "include": ["src/**/*"],
 "exclude": ["node_modules","**/*.spec.ts"]
}

我收到此警告

No inputs were found in config file 'c:/Users/EHHD05911.COMMUN/Documents/cockpitLight/DB mananger/tsconfig.json'. Specified 'include' paths were '["src//"]' and 'exclude' paths were '["node_modules","/.spec.ts"]'


您无法直接运行无法运行的节点app.ts文件
您需要像babel js或typescript编译器tsc这样的转译器,因此首先转译为js文件,然后运行node app.js


我怀疑您要导入的任何内容都具有typescript语法(强类型输入等),因此直接运行node将不起作用。您需要先运行tsc,这会将所有内容转换为dist文件夹中的javascript,然后运行node dist/app.js

这有点麻烦,这就是为什么有ts-node的原因。听起来确实像是typescript的节点REPL。您应该能够运行ts-node src/app.ts


您正在使用.js扩展名,您需要.ts扩展名,例如:app.ts而不是app.js

确保在npm global或dev依赖项中都有typescript。


使用babel js是一种工具链,主要用于在当前和较旧的浏览器或环境中将ECMAScript 2015代码转换为JavaScript的向后兼容版本。

package.json

1
2
3
4
5
6
7
8
"dependencies": {
"@babel/polyfill":"^7.0.0",
}

"babel": {
"presets": [
 "@babel/preset-env"
]

},

1
2
3
"scripts": {
   "start":"server.js --exec babel-node",
}

https://babeljs.io/docs

这将启用/解析您的导入语句。


import { something }是一种typescript语法,在.js文件中不起作用。那是一种独立的语言。尝试改用require