gpt4 book ai didi

javascript - 在另一个模块中使用一个模块。 module.exports 是空对象

转载 作者:行者123 更新时间:2023-12-03 02:32:16 25 4
gpt4 key购买 nike

我有一个模块想在不同的项目中使用。它是使用webpack3编译的。在第二个项目中,我链接到第一个模块,这似乎有效,除了当我需要该模块时,它总是作为空对象返回。

tsconfig 选项

{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"sourceMap": true,
"outDir": "./dist",
"strict": true,
"allowJs": true,
"lib": [
"es2015"
]
}
}

dist/index.js(缩短)

/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var Test = /** @class */ (function () {
function Test() {
}
Test.prototype.test = function () {
console.log('works');
};
return Test;
}());
exports.Test = Test;


/***/ })
/******/ ]);

package.json(缩短)

{
"main": "dist/index.js",
}

这归结为一个名为“test”的模块,一个名为 Test 的类,其中还包含一个名为 Test 的方法。

如果我在第一个项目上运行 module.exports,它是一个空对象。

在已链接到它并将其包含在其 Node 模块中的第二个项目中。

const test = require("test");
console.log(test); // {}

如果我从另一个 Node 模块复制代码,并将其粘贴到 dist/index.js 之上,它确实会返回预期的结果。

  • 导出的 webpack 配置是否也需要通过 webpack 导入?我希望它能在许多项目中使用,无论它们是否使用 webpack。

感谢您的帮助,我觉得我快要成功了,但还没有完全实现。

最佳答案

也许这个 github 问题可以帮助你

Can't require bundle on node.js

在 webpack 配置文件中设置这些

target: "node" 
output.libraryTarget: "commonjs"

关于javascript - 在另一个模块中使用一个模块。 module.exports 是空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48686157/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com