我正在尝试制作一个 NPM 包,让其他人可以在运行 npm install <package>
后使用我的类来实例化它。 。截至目前,它在开发中运行良好,但通过 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';
main.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 存储库。
最佳答案
假设这是一个 typescript 项目(通过这个问题的标签),这似乎是配置问题,需要通过在 package.json
和 webpack 上进行正确设置来解决配置文件
。
如果您可以分享 package.json
中的内容,将会很有帮助,但我认为查看 npm script hooks尝试将钩子(Hook)与 webpack 构建 cli 脚本正确链接将是解决您的问题的一个很好的起点。
我建议您确保:
- Webpack 构建过程(或用于 typescript 编译的任何方法)与本地的
npm install
之后触发的钩子(Hook)链接,当有人安装你的包时,该钩子(Hook)会自动运行通过npm install
- 已编译的 javascript 包通过您的 package.json 正确公开
至少,您可能需要检查是否需要实际编译 TypeScript 源代码,具体取决于您是否仅支持 TypeScript。
这是题外话,但不要使用 webpack,除非你确实需要使用 webpack。通常,如果您正在编写 npm 模块,那么使用 typescript 编译器本身就足够了。
关于javascript - <Class> 不是构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51509761/