简体   繁体   English

试图制作 NPM package

[英]Trying to make an NPM package

Basically, im trying to make a package that would look like this in my main project file基本上,我试图在我的主项目文件中制作一个看起来像这样的 package

const package = require("package");
const newPackage = new package({
  param: 'value',
  otherParam: 'otherValue'
});

and then in every other project file I could use然后在我可以使用的所有其他项目文件中

const { someFunction } = require('package')

someFunction()

and then the SomeFunction() function should return value and otherValue without needing to do然后SomeFunction() function 应该返回valueotherValue而不需要做

const package = require("package");
const newPackage = new package({
  param: 'value',
  otherParam: 'otherValue'
});

newPackage.someFunction()

in every project file.在每个项目文件中。

Im not sure how to do this or if this is even possible, but would love something that would work like (or similar to) this.我不确定如何做到这一点,或者这是否可能,但我会喜欢类似(或类似)这样的东西。

While it would be possible to do this, it would involve some pretty smelly code - the package would have to have calling the constructor produce side-effects and return an unused instance.虽然可以做到这一点,但它会涉及一些非常臭的代码 - package 必须调用构造函数产生副作用并返回一个未使用的实例。 For a very slight tweak, consider instead if you could change the init code from对于非常细微的调整,请考虑是否可以更改初始化代码

const package = require("package");
const newPackage = new package({
  param: 'value',
  otherParam: 'otherValue'
});

to something like类似于

const { init } = require("package");
init({
  param: 'value',
  otherParam: 'otherValue'
});

That would be quite doable and not smelly.那将是非常可行的,而且不臭。 Put a variable in the package's scope that gets assigned to when init is called, and return that variable when someFunction is called.将一个变量放入包的 scope 中,在调用init时分配给该变量,并在调用someFunction时返回该变量。

let initObj;
module.exports = {
  init(obj) {
    initObj = obj;
  },
  someFunction() {
    return initObj;
  }
};

Live snippet:实时片段:

 const theModule = (() => { let initObj; return { init(obj) { initObj = obj; }, someFunction() { return initObj; } } })(); theModule.init({ param: 'value', otherParam: 'otherValue' }); console.log(theModule.someFunction());

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

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