Open AndrewRot opened 4 years ago
This is actually a feature that should be documented. If you export a function, them preval will call that function and whatever you return will be the thing used for replacement. Meaning you could return a function if you want:
function doThing(message) { return message + ' a thing'; }
module.exports = () => doThing;
Would you like to update your pull request to add documentation for this feature?
Recently I needed to "generate" a function and thought about the following method:
const getAssets = preval`module.exports = require('./build-time/get-assets')`
const assets = preval`module.exports = { run: () => ({${getAssets}}) }`.run()
getAssets
returns something like: require('./image-path-1'); require('./image-path-2'); ...
.
assets
puts this string into the function body, generating something like:
{
run: () => { require('./image-path-1'); require('./image-path-2'); ...}
}
Doubts:
Sorry for my English, I'm a beginner at this.
You should probably be using babel-plugin-codegen which is more powerful.
I have a similar needs, I was trying out this tool and got nicely surprised at beginning but then I just tried to put a condition and then :boom:
Second point super annoying is I would like to preserve my modules from beginning to end and output es2020 code in the end.
My goal is to have a kind of builder pattern that could be statically replaced. Example:
// Builder declared in the spoiler
export const request = (str) => {
let cond = builder().foo("bar").num(1);
if (str) {
return cond.str(str).build();
}
return cond.build();
}
// Statically built as
export const request = (str) => ({
foo: 'bar',
num: 1,
...(str ? { str } : {}),
})
Of course this is a minimal example but each step would impact several attributes in that object and it would be great to be built as a single object with conditionals spreading for instance.
Any help/news on this?
So I was trying to use
preval
to insert functions into my code before run time. What I thought was going to be quite trivial, turned out to be a bit tricky. In order to insert functions,preval
implicitly requires you to wrap your exports in an object.Example function:
Usage of preval:
Generated code:
explanation A
Preval then creates an object with our function inside. This is a bit funky for users. If you attempt to do this without wrapping your exports as an object, preval will fail to inject the function with the following behavior:
confusing failed scenario to insert function
Example function:
Usage of preval:
Generated code:
Suggestion
A.) To make this easier for users to insert functions into their code, you may want to consider the way
preval
requires modules. B.) Add an example to theREADME.md
that illustrates how this is done.