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

标签 javascript node.js module

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

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/

相关文章:

javascript - 将变量传递给回调函数

logging - Prestashop Logger::addLog() 在哪里保存日志文件?

javascript - 基于 process.env.NODE_ENV 的条件导出 ES6 模块的可能性?

javascript - 我可以将文本附加/绑定(bind)到 Raphael 中的元素吗?

javascript - 在 d3 js 中切割底部圆弧的矩形

javascript - 如何使用javascript在网格布局中定位div

c - 在可加载的 linux 内核模块上设置 cpu 亲和性

javascript - 从内容上方的重叠区域中删除三 Angular 形的阴影?

javascript - 如何使用 javascript 设置具有非空值的 firestore 文档字段

javascript - 如何在elasticsearch中向elasticsearch UpdateByQuery添加url参数