简体   繁体   English

将数据传递到自定义npm软件包模块

[英]Pass data to custom npm package module

I'm new to building custom npm packages and I'm getting lost configuring it with data coming from the application it is using it. 我是构建自定义npm软件包的新手,并且迷失了使用来自它正在使用的应用程序的数据来配置它的信息。

EDIT: This is just an example but the app will have more methods and those fake a and b will be used from many of those methods. 编辑:这只是一个例子,但是应用程序将具有更多方法,并且其中许多方法将使用假a和b。

Basically on App I'm requiring my package in this way: 基本上在App上,我需要这样的包装:

var a = 'a';
var b = 'b';
var module = require('module')(a, b);
module.test();

My module in his index file has: 我在他的索引文件中的模块具有:

var a;
var b;

function test() {
  return {
    a: a,
    b: b
  };
}

module.exports = function(_a, _b) {
  a = _a;
  b = _b;

  return {
    test: test
  }
};

As you can guess it is not working as I was expecting... How can I pass my custom data to my npm package and be able using that data along my methods? 如您所料,它没有按我预期的那样工作...如何将自定义数据传递给npm包,并能够在我的方法中使用这些数据?

shouldnt you use it something like this 你不应该使用这样的东西

var a = 'a';
var b = 'b';
var module = require('module');
module.init(a,b);

// do some other code....

module.test();

and in your module like this: 并在您的模块中像这样:

var _a = null;
var _b = null;
var test = function() {
    return {
        a: _a,
        b: _b
    }
}

var init = function(a, b) {
    _a = a;
    _b = b;
}

module.exports = {
    init,
    test
};

Your definition of a module is absolutely fine but it depends on how you plan on using it! 您对模块的定义绝对正确,但这取决于您计划使用它的方式!

If you would like to use it as though it were published on the npm-registry then you need to use the process described here: Installing a local module using npm? 如果您想使用它,就像发布在npm-registry上一样,则需要使用此处描述的过程: 使用npm安装本地模块?

I know that this is an example but for other readers - you shouldn't use the name module as this is already in use by Node. 我知道这是一个示例,但对于其他读者-您不应该使用名称module因为Node已经使用了名称module

If you are simply using a modular approach to producing a larger app and you want to use the exports of your file, then you require the file by pointing to it. 如果您只是使用模块化方法来生产更大的应用程序,并且想要使用文件的导出,则需要通过指向文件来要求文件。 For example, if this file was called module.js and is in the same directory as the script which is requiring it then use: 例如,如果此文件名为module.js并且与需要该文件的脚本位于同一目录中,则使用:

  var myModule = require('./module.js')(a, b);

If you have it in another directory then use the normal relative path navigation syntax like ../module.js if it is up one directory or ./lib/module.js if it is in a sub-directory called lib 如果在另一个目录中,则使用普通的相对路径导航语法,例如../module.js如果它在一个目录中)或./lib/module.js如果在一个名为lib的子目录中)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM