我在TS中有以下代码,可以在Express中创建ConnectRoles中间件的实例:

let user = new ConnectRoles(config);

这是中间件希望能够初始化的内容,即对构造函数的简单调用,但是在编译后,生成的javascript代码如下所示:

let user = new connect_roles_1.default(config);

我正在使用以下方法在TS中导入此类:

import ConnectRoles from "connect-roles";

转换为:

const connect_roles_1 = require("connect-roles");

在JS中,我实例化/导入类的方式可能是这里的问题吗?我可以手动删除导致JS代码错误的“默认”方法,但这违背了使用编译器的目的,特别是在类似情况开始频繁发生时。

还有一件事,这是我的tsconfig.json:

{
  "compilerOptions": {
      "baseUrl": ".",
      "paths": { "*": ["types/*"] },
      "target": "es2015",
      "module": "commonjs",
      "moduleResolution": "node",
      "isolatedModules": false,
      "jsx": "react",
      "experimentalDecorators": true,
      "emitDecoratorMetadata": true,
      "declaration": false,
      "noImplicitAny": false,
      "noImplicitUseStrict": false,
      "removeComments": true,
      "noLib": false,
      "preserveConstEnums": true,
      "suppressImplicitAnyIndexErrors": true,
      "outDir": "app",
      "sourceMap": true,
      "watch": true
  },
  "exclude": [
      "node_modules",
      "typings/browser",
      "typings/browser.d.ts",
  ],
  "compileOnSave": true,
  "buildOnSave": true,
  "atom": {
      "rewriteTsconfig": false
  }
}


任何想法将不胜感激,谢谢!

最佳答案

正如Tobiq所说,import ConnectRoles from "connect-roles"试图导入默认的导出。但是,您尝试导入的模块不使用默认导出;而是使用module.exports = ConnectRoles

这是三种不同的导入样式及其产生的编译结果:

import ConnectRolesImport from 'connect-roles';
const connectRolesImport = new ConnectRolesImport(); // error!

import * as ConnectRolesImportAll from 'connect-roles';
const connectRolesImportAll = new ConnectRolesImportAll();

import ConnectRolesRequire = require('connect-roles');
const connectRolesRequire = new ConnectRolesRequire();


编译结果:

var connect_roles_1 = require("connect-roles");
var connectRolesImport = new connect_roles_1["default"]();

var ConnectRolesImportAll = require("connect-roles");
var connectRolesImportAll = new ConnectRolesImportAll();

var ConnectRolesRequire = require("connect-roles");
var connectRolesRequire = new ConnectRolesRequire();


这是TypeScript team members之一,讨论了import xxx as...import xxx = require...语法之间的区别。那和这个答案的评论将帮助您选择使用哪个。

10-07 20:05