如何在require中传递字符串/对象

how to pass a string/object in a require

本文关键字:字符串 对象 require      更新时间:2023-10-11

我想在javascript模块中传递一个字符串

模块1.js

  var currency = 'dollar'
  module = require('./module2')(currency)

我该怎么做,因为现在我有这个错误

TypeError: string is not a function e=[TypeError:string is not a function]

感谢所有

 var currency = 'dollar'
 module = require('./module2').yourFunction(currency);

我认为你必须在模块内部构建函数,而不是在需要后调用它,这是解决问题的更好方案change.js

module.exports = {
  escape: function(html) {
    return String(html)
      .replace(/&/g, '&')
      .replace(/"/g, '"')
      .replace(/'/g, ''')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;');
  }

这样称呼

var change= require("change");
change.escape(yourElement);

如果您想将货币作为参数传递给模块2中的函数,请使用:

module=require('./module2').FunctionName(货币);

如果您想访问模块2中的名称货币属性(在本例中为"美元"属性),请使用:

module=require('./module2')[货币];