[英]making Ramda.js functions globally accessible (without R. )
I want to use Ramda.js functions without typing R.
我想在不输入R.
情况下使用Ramda.js函数R.
I've tried to add all the functions to the global scope but it doesn't work this is my try 我试图将所有函数添加到全局范围但它不起作用这是我的尝试
const R = require('ramda'); // R is an object containing lots of functions
for(let x in R) {
global.x = x;
}
also, I want to know how to do it using Ramda library itself. 另外,我想知道如何使用Ramda库本身。
Make sure you are setting the property called x, rather than the x property: Also, be sure to assign the value of R[x]
back, rather than the property name x
确保设置名为x的属性,而不是x属性:另外,请确保将R[x]
的值赋值,而不是属性名称x
global[x] = R[x];
You could also try iterating through getOwnPropertyNames: 您还可以尝试迭代getOwnPropertyNames:
for (const prop of Object.getOwnPropertyNames(R)) {
global[prop] = R[prop]
}
Or, if applicable, just destructure the properties you need into your scope: 或者,如果适用,只需将您需要的属性解构为范围:
const {someProp, someOtherProp} = R;
As per comments, while I disagree that typing additional 2 characters could be termed as a fuss, but it is how you feel. 根据评论,虽然我不同意输入额外的2个字符可能被称为大惊小怪,但它是你的感受。
Like @uber5001 mentioned the de-structure technique, it is one way, but it means you first need to require
entire ramda functions into R
then retrieve the functions you need. 如@ uber5001提到脱结构技术,它是一种方式,但它意味着你首先需要require
整个ramda功能为R
然后检索您需要的功能。
You can also require
only the required functions: 您也可以require
只需要的功能:
const uniq = require('ramda/src/uniq')
const zip = require('ramda/src/zip')
// and so on
HTH HTH
Setting all the functions of Ramda as globals might be risky. 将Ramda的所有函数设置为全局变量可能存在风险。 Ramda has a lot of functions, and some of them might override existing globals you have. Ramda有很多功能,其中一些可能会覆盖你现有的全局变量。 A better practice (which is still considered a bad practice because you can still shadow-name variables) is the with
statement, which destructures all the properties of the object while not overriding your outer scope variables. 更好的做法(仍然被认为是一种不好的做法,因为你仍然可以使用阴影名称变量)是with
语句,它可以在不覆盖外部作用域变量的情况下解构对象的所有属性。
with(R) {
pipe(
map(x => x ** 2),
filter(x => x > 24)
)([3, 4, 5, 6]); // => [25, 36]
}
Note that the with statement is disabled in strict mode. 请注意,在严格模式下禁用with语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.