gpt4 book ai didi

javascript - 使用模块 require() 参数的不同方式?

转载 作者:行者123 更新时间:2023-11-30 20:43:19 45 4
gpt4 key购买 nike

如果你想将参数传递给模块,你可以这样做:

index.js

let test = require("./module.js")(something);

module.js

module.exports = (something) => {
//Working with `something` here
};

但是有没有不用 module.exports = (var) => {} 的方法呢?

更具体地说,能够在函数容器外部编写示例代码,然后在文件末尾执行 module.exports

或者您可以这样做吗?

const globalSomething;

(something) => {
globalSomething = something;
}

module.exports = heavyWorkWith(globalSomething);

如果你懂我的话。

最佳答案

您不局限于使用未命名函数来传递参数,您可以使用命名函数

export default function myExport(something) {
//...
}

甚至一个类(class)

export default class myExport() {
constructor(something) {
//...
}
}

在反面,导入:

const myExport = require('./myModuleOrWhatever');
const foo = new myExport(something);

更重要的是,您可以通过匿名模块导出来传递模块常量

const bar = somethingElse;
const baz = moreElse;

/*
alernatively
export default const bar = somethingElse
*/
module.exports = {
foo: (something) => {
//Working with `something` here
},
bar,
baz,
};

关于javascript - 使用模块 require() 参数的不同方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49014120/

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