首页 > 解决方案 > 使用打字稿在Node js中导入类

问题描述

我会在 nodejs 中导入类并在其中使用它app.ts

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);

当我尝试编译时,我得到了这个错误。

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

我创建了 tsconfig 文件:

{
  "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"]
}

我收到此警告

在配置文件“c:/Users/EHHD05911.COMMUN/Documents/cockpitLight/DB mananger/tsconfig.json”中找不到输入。指定的 'include' 路径是 '["src/ / "]' 和 'exclude' 路径是 '["node_modules"," / .spec.ts"]'

标签: node.jstypescript

解决方案


您不能直接运行 node app.ts 文件,这将不起作用您需要像 babel js 或 typescript 编译器 tsc 这样的转译器,因此首先转译为 js 文件,然后运行 ​​node app.js


推荐阅读