【问题标题】:<Class> is not a constructor<Class> 不是构造函数
【发布时间】:2018-07-25 01:51:54
【问题描述】:

我正在尝试制作一个 NPM 包,在他们运行 npm install &lt;package&gt; 之后,有人可以使用我的类来实例化它。截至目前,它在开发中运行良好,但通过 webpack 捆绑后,我使用 npm 安装包,但它立即被 TypeError: index_1.MyClass is not a constructor 炸毁

my-class.ts

export class MyClass {
    constructor() {

    }
    method1(): void {
        console.log('im a method!');
    }
}

index.ts

export { MyClass } from './my-class';

ma​​in.ts(我使用 npm install 的主要应用程序代码)

import { MyClass } from 'npm-package-directory';

const myClass = new MyClass(); // <-- exception thrown
myClass.method1();

webpack.config.js

const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
    plugins: [
        new CopyWebpackPlugin([
            {
                from: 'package.json',
                to: 'package.json',
                toType: 'file'
            }
        ]),
        new CopyWebpackPlugin([
            {
                from: 'README.md',
                to: 'README.md',
                toType: 'file'
            }
        ])
    ],
    devtool: 'source-map',
    entry: './src/my-class.ts',
    resolve: {
      extensions: [
          '.ts'
      ]
    },
    output: {
        path: __dirname + '/dist',
        filename: '[name].js'
    },
    module: {
        rules: [
            // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
            { test: /\.ts?$/, loader: 'ts-loader' }
        ]
    },
    target: 'node'
}

我尝试了多种不同风格的导出类,但每次都遇到相同的异常。我尝试了许多类似于this one 的其他 SOF 问题,但没有运气。我去哪儿了?

注意以上是示例代码,旨在简化问题,但很乐意提供实际设置的 github 存储库。

【问题讨论】:

  • 它是一个角度应用程序吗?您是否在 app.module.ts 中导入了模块?
  • 不,不是 Angular 应用程序。这是直接的 TypeScript/Node。 Angular 会让我需要在编译时将它添加到我的 app.module.ts 中变得更加明显。这一路编译没有任何错误。只是运行时错误。
  • 目前我的 webpack.config.js 正在走这条路……

标签: javascript typescript ecmascript-6 es6-modules


【解决方案1】:

假设这是一个打字稿项目(通过这个问题的标签),这似乎是配置问题,需要通过正确设置package.jsonwebpack config file 来解决。

如果您可以分享 package.json 中的内容会很有帮助,但我认为查看 npm script hooks 并尝试将钩子与 webpack 构建 cli 脚本正确链接将是解决您的问题的一个很好的起点.

我建议你确定:

  1. Webpack 构建过程(或您用于 typescript 编译的任何方法)与本地 npm install 之后触发的钩子相关联,当有人通过 npm install 安装您的包时自动运行该钩子
  2. 已编译的 javascript 包通过您的 package.json 正确公开

至少,您可能需要检查是否需要实际编译您的 typescript 源代码,具体取决于您是否仅支持 typescript。

这是题外话,但除非你真的需要使用 webpack,否则不要使用 webpack。如果您正在编写 npm 模块,通常使用 typescript 编译器本身就足够了。

【讨论】:

  • 这里是完整的 repo(非常小)。 github.com/mswilson4040/chadwick-to-mongo
  • 我想你在这里对 webpack 的使用可能是对的。由于这是一个节点模块,webpack 可能有点矫枉过正。似乎 webpack 是问题所在,我只需要一个不同的构建过程。我只是真的在挖掘 webpack 的魅力,并想用它来玩。
  • 嗨@mwilson,嗯,我认为在你的 package.json 上添加 webpack compile cli 命令的 post install 钩子,并将 webpack 编译依赖项移至dependency(非开发人员)将解决你的问题。 (这也可能包括typings modules
  • 但是现在这将引入(如果你足够关心的话)你的模块用户需要安装 webpack 作为依赖项来编译你的 npm 模块的问题。如果您只需要编译打字稿,只需运行tsc 就足够了(但现在您需要正确设置 tsconfig.json)
  • 谢谢@kairun。我会试一试,看看我能走多远。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-10-12
  • 2016-04-07
  • 2017-10-12
  • 2023-01-17
  • 2021-08-31
  • 2013-07-10
  • 1970-01-01
相关资源
最近更新 更多