【问题标题】:TypeScript project in NPM not a constructorNPM 中的 TypeScript 项目不是构造函数
【发布时间】:2020-07-02 01:41:06
【问题描述】:

我有一个使用 TypeScript 构建的 npm 模块。我似乎无法 require() 其他代码中的模块

MyClass4TS myclass4ts.ts

class MyClass4TS {

    constructor(){

    }
}

export { MyClass4TS } 

编辑:

还尝试将导出附加到类,但没有效果

export default class MyClass4TS {

    constructor(){

    }
}

MyClass4TS package.json

{
  "name": "myclass4ts",
  "version": "0.0.1",
  "description": "blahblahblah",
  "main": "dist/myclass4ts.js",
  "scripts": {
    "build": "tsc",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://somegitrepo.git"
  },
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://somegitrepo/issues"
  },
  "homepage": "https://somegitrepo#readme",
  "devDependencies": {
    "typescript": "^3.8.3"
  },
  "dependencies": {
    "@types/node": "^13.9.2"
  }
}

然后我 npm 直接从 git 安装模块......并且成功了。现在我尝试使用它并且..

var MyClass4TS = require('MyClass4TS')

var api = new MyClass4TS()

api.execute_post("@@@")

导致这个错误

/path/to/project/myclass4ts_test.js:3
var api = new MyClass4TS()
          ^

TypeError: MyClass4TS is not a constructor
    at Object.<anonymous> (/path/to/project/myclass4ts_test.js:3:11)
    at Module._compile (internal/modules/cjs/loader.js:1158:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
    at Module.load (internal/modules/cjs/loader.js:1002:32)
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
    at internal/main/run_main_module.js:18:47
(base) % 

tsconfig.json

{
  "compilerOptions": {
    /* Basic Options */
    // "incremental": true,                   /* Enable incremental compilation */
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    // "lib": [],                             /* Specify library files to be included in the compilation. */
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    "outDir": "./dist",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                     /* Enable project compilation */
    // "tsBuildInfoFile": "./",               /* Specify file to store incremental compilation information */
    // "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                           /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

    /* Module Resolution Options */
    "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
    // "allowUmdGlobalAccess": true,          /* Allow accessing UMD globals from modules. */

    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */

    /* Advanced Options */
    "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
  }
}

【问题讨论】:

  • 您的模块导出一个对象,而不是一个类。该对象只是包含类。
  • 对不起,我还在挑选这个 TS / JS..
  • 我要放弃{ }s 吗?
  • 如果它是模块中唯一的东西,你可以只export default class ...。阅读typescriptlang.org/docs/handbook/modules.html
  • 我输入了 export default MyClass4TS 并尝试了 agin,但得到了 Error: Cannot find module 'MyClass4TS' 我一直在阅读该文档,但会继续尝试,谢谢您的洞察力

标签: typescript


【解决方案1】:

你使用的export 语法应该会给你一个提示:

export { MyClass4TS } 

您导出一个具有类 MyClass4TS 的对象作为也名为 MyClass4TS 的属性的值。

{ MyClass4TS } 的语法实际上是 JS 提供的一种写{ MyClass4TS: MyClass4TS } 的快捷方式。如您所见,这个就是上面描述的 JavaScript 对象。

如果您不使用export default,则模块会为您尝试的两种语法变体导出一个对象。

import(在 TypeScript 中)的语法类似:

import { MyClass4TS } from 'MyClass4TS';

它使用object destructuring 导入模块“MyClass4TS”导出的对象,并将其名为MyClass4TS 的属性值存储到名为MyClass4TS 的变量中(由import 隐式声明)。

TypeScript 编译器从上面一行生成的 JavaScript 代码如下所示:

const MyClass4TS_module = require('MyClass4TS');

变量MyClass4TS_module的值就是上面导出的对象。因此,MyClass4TS 类可以作为MyClass4TS_module.MyClass4TS 访问。

您也可以使用对象解构来仅提取您需要的模块“MyClass4TS”的属性:

const { MyClass4TS } = require('MyClass4TS');

const instance = new MyClass4TS();

【讨论】:

  • 我实际上自己解决了这个问题,但是既然你做了这么好的解释.. 我想给你点。谢谢 !我最终尝试了两次,直到我尝试从我的消费 nodejs 中请求,而不是导入..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-10
  • 1970-01-01
  • 2020-03-02
  • 1970-01-01
  • 2016-06-03
  • 2018-02-12
相关资源
最近更新 更多