typescript 没有'new'就不能调用类构造函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49741791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:20:43  来源:igfitidea点击:

Class constructor cannot be invoked without 'new'

javascriptnode.jstypescript

提问by GlGuru

Appreciate that this questions has been asked a few times, but almost all the cases that I've encountered have been the ones where someone tried to extend a non-native class. My case is different. I have a very simple base class called CObjectwhich is as follows:

感谢这个问题已被问过几次,但我遇到的几乎所有情况都是有人试图扩展非本地类的情况。我的情况不同。我有一个非常简单的基类CObject,如下所示:

export class CObject extends BaseObject {
    constructor() {
        super();
    }
    static url(path: string): string { return ""; }
    static wssUrl(): string { return ""; }
    static callMethod(method, path: string, params: any, noConvertData?: boolean): Promise<any> { return null; }
    static post(path: string, params: any, noConvertData?: boolean): Promise<any> {
        return CObject.callMethod('post', path, params, noConvertData);
    }

    static put(path: string, params: any, noConvertData?: boolean): Promise<any> {
        return CObject.callMethod('put', path, params, noConvertData);
    }

    static patch(path: string, params: any, noConvertData?: boolean): Promise<any> {
        return CObject.callMethod('patch', path, params, noConvertData);
    }

    static get(path: string, params: any, noConvertData?: boolean): Promise<any> {
        return CObject.callMethod('get', path, params, noConvertData);
    }

    static delete(path: string, params: any, noConvertData?: boolean): Promise<any> {
        return CObject.callMethod('delete', path, params, noConvertData);
    }
}

The entire hierarchy of classes including BaseObject, are just simple Typescript classes. However, when I extend a class from CObjectand then try instantiating it, I get this dreaded error (4 days now!). The funny thing is that I can instantiate CObjecton it's own without any issues. It's just derived classes that are giving the issue, even empty ones like this:

包括 BaseObject 在内的整个类层次结构只是简单的 Typescript 类。但是,当我扩展一个类CObject然后尝试实例化它时,我得到了这个可怕的错误(现在 4 天了!)。有趣的是,我可以CObject毫无问题地自行实例化。只是派生类出现了问题,甚至是像这样的空类:

export class TestClass extends CObject {
    constructor() {
        super();
    }
}

A point to note is that this code is shared between my Server (Node.js) and Client sides. The code works perfectly fine on the server side. No issues whatsoever. I have tried looking at the babel generated code and it's just simple ES6 classes. All other TS generated classes work as fine and everything below CObjectfails when it gets to calling the CObjectconstructor.

需要注意的一点是,此代码在我的服务器 (Node.js) 和客户端之间共享。该代码在服务器端运行良好。没有任何问题。我试过查看 babel 生成的代码,它只是简单的 ES6 类。所有其他 TS 生成的类都可以正常工作,并且CObject在调用CObject构造函数时下面的所有内容都失败了。

My .babelrc is given below:

我的 .babelrc 如下:

{
    "presets": [
        "es2015-node5",
        "react",
        "stage-0",
        "stage-1",
        "bluebird"
    ],
    "plugins": [
        "transform-decorators-legacy",
        "react-hot-loader/babel",
        "transform-async-to-bluebird",
        "transform-promise-to-bluebird",
        "transform-runtime",
        [
            "module-alias", 
            [
                { "src": "./build/Server", "expose": "Server" },
                { "src": "./build/Shared", "expose": "Shared" },
                { "src": "./build/Client", "expose": "Client" }
            ]
        ]
    ],
    "compact": "false"
}`

For client side compilation, my awesome-typescript-loader config in tsconfig.json is as follows:

对于客户端编译,我在 tsconfig.json 中的 awesome-typescript-loader 配置如下:

EDIT: I was looking at the wrong ATL config. The full config is as follows:

编辑:我正在查看错误的 ATL 配置。完整配置如下:

"awesomeTypescriptLoaderOptions": {
    "babelrc": true,
    "useBabel": true,
    "useWebpackText": true,
    "useTranspileModule": true,
    "doTypeCheck": true,
    "forkChecker": true,
    "presets": ["env", { "targets": "last 2 versions, ie 11", "modules": false }, { "exclude": ["transform-es2015-classes"] } ],
    "babelOptions": {
        "sourceMaps": true
    },
    "useCache": true
}

Client side webpack config is as follows:

客户端 webpack 配置如下:

var path = require('path');
var webpack = require('webpack');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');

let outputDir = path.join(__dirname, "..", "dist", "Client");
console.log(`Output: ${outputDir}`);

module.exports = {
    entry: "./src/Client/Browser/Src/Main.tsx",
    output: {
        filename: "client.js",
        path: outputDir
    },
    target: 'web',

    // Enable sourcemaps for debugging webpack's output.
    devtool: "source-map",

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: [".ts", ".tsx", ".js", ".json"],
        plugins: [new TsconfigPathsPlugin({ configFile: "./tsconfig.json" })],
        modules: [
            "./node_modules",
            "./src/Shared",
            "./src/Client"
        ]
    },

    module: {
        rules: [
            // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
            { test: /\.tsx?$/, loader: "awesome-typescript-loader" },

            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            { enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
        ]
    }
};

Any help will be appreciated. Thank you.

任何帮助将不胜感激。谢谢你。

Edit: The exact error is:

编辑:确切的错误是:

ConfigSection.ts?26cc:18 Uncaught TypeError: Class constructor CObject cannot be invoked without 'new'
    at new ConfigSection (ConfigSection.ts?26cc:18)
    at Object../src/Shared/Model/Config/ShAlpha.ts (ShAlpha.ts:338)
    at __webpack_require__ (bootstrap:19)

采纳答案by GlGuru

Ok, thanks to Oscar Paz, I have been able to fix the issue. Turns out that the culprit was my ATL config:

好的,感谢 Oscar Paz,我已经能够解决这个问题。原来罪魁祸首是我的 ATL 配置:

"awesomeTypescriptLoaderOptions": {
    "babelrc": true,
    "useBabel": true,
    "useWebpackText": true,
    "useTranspileModule": true,
    "doTypeCheck": true,
    "forkChecker": true,
    "presets": ["env", { "targets": "last 2 versions, ie 11", "modules": false }, { "exclude": ["transform-es2015-classes"] } ],
    "babelOptions": {
        "sourceMaps": true
    },
    "useCache": true
}

More specifically, this line:

更具体地说,这一行:

    "presets": ["env", { "targets": "last 2 versions, ie 11", "modules": false }, { "exclude": ["transform-es2015-classes"] } ],

even though I'd set:

即使我设置:

    "babelrc": true,

Expecting the .babelrc to get used, which is what was getting used for the Node.js code. This was causing multiple definitions (both ES6 and ES5) of the classes derived from CObjectto be generated. So CObjectwas getting generated correctly:

期望 .babelrc 被使用,这就是用于 Node.js 代码的内容。这导致CObject生成派生类的多个定义(ES6 和 ES5)。所以CObject被正确生成:

let CObject = exports.CObject = class CObject extends _BaseObject.BaseObject {} ...

The first definition of ConfigSectionwas also getting generated correctly:

的第一个定义ConfigSection也被正确生成:

let ConfigSection = ConfigSection_1 = class ConfigSection extends Shared_Core_CObject__WEBPACK_IMPORTED_MODULE_1__["CObject"] {} ...

But then further down:

但再往下走:

var ConfigSection = ConfigSection_1 = function (_CObject) {
    (0, _inherits3.default)(ConfigSection, _CObject); ...

This is what was causing the error. I don't know why ATL isn't ignoring those options and why those options cause this sort of code-gen. Perhaps, someone with a better understanding can shed some light.

这就是导致错误的原因。我不知道为什么 ATL 不忽略这些选项以及为什么这些选项会导致这种代码生成。也许,有更好理解的人可以解释一下。

回答by Offirmo

For fellow Googlers, another cause of this error: on 04/2019, using the non maintained why-did-you-updatenpm React module caused this error.

对于其他 Google 员工,此错误的另一个原因是:在 2019 年 4 月,使用非维护的为什么要更新npm React 模块导致了此错误。

Removing the module and its invocation fixed the bug.

删除模块及其调用修复了错误。