【发布时间】:2019-12-13 16:14:27
【问题描述】:
我有两个模块,一个用ts 编写,另一个用js 编写。需要在ts 模块中访问js 模块中的实用程序之一。
所以实用程序service.js如下,
module.exports = {
helloFriends: function (message) {
console.log(message);
}
}
console.log('This part should not get invoked');
调用caller.ts如下,
import { helloFriends } from './../moduleb/service';
helloFriends('Hello');
上面tsc caller.ts的输出然后node caller.js的输出如下,
This part should not get invoked
Hello
我不希望从service.js 调用除函数helloFriends 之外的任何其他代码,我该怎么办?
注意:这两个模块是相互独立的,有自己的节点依赖关系。
更新:1
我处理了一个 hack,我在两个模块 .env 文件中定义了 IAM。
对于service.js .env 有IAM=service,
对于caller.ts .env 有IAM=caller,
所以如果 service.js 是从它自己的模块调用的,IAM 是 service 但是当它是从外部调用时,例如从caller.ts 开始,它的IAM 值为caller,然后在service.js 中我做了以下更改:
在service.js我做了如下修改:
var iam = process.env.IAM;
module.exports = {
helloFriends: function (message) {
console.log(message);
}
}
if (iam === 'service') {
console.log('This part should not get invoked, When called by external modules other than service');
}
所以根据调用者的配置,我决定是否执行特定的代码部分。
.envhttps://www.npmjs.com/package/dotenv使用的插件
更新:2
根据我在这个问题后获得的经验,更好的方法是让函数服务于每个目的/功能并单独导出它们。
【问题讨论】:
-
虽然投反对票添加评论会有所帮助,谢谢
-
不是我的反对意见,但您已经尝试过什么?你不能直接删除代码,或者把它放在一个导出的方法中吗?
-
没有投反对票,但 AFAIK 这是不可能的。我相信
require/import将贯穿文件的内容,包括执行任何函数调用。见这里:stackoverflow.com/a/37325716/3813411 -
Caramiriel & rb612 感谢您的建议,它帮助我推断出答案。
标签: javascript node.js typescript webpack