kentcdodds / kentcdodds/babel-plugin-preval
Simplify function injection
- Dominant language
- TypeScript
- Stars
- 1.4k
- Forks
- 48
- PR merge metrics
- No merged PRs in 30d
Description
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:
```js
function doThing(message) { return message + ' a thing'; }
module.exports = { doThing }; // You must wrap it here [see explanation A below]
```
Usage of preval:
```js
const doThing = preval.require('./doDigest.js').doThing; // pull out function from object
// In order to insert a function, you must wrap it in an object and then extract it
```
Generated code:
```js
var doThing = {
"doThing": function doThing(message) {
return message + ' a thing';
}
}.doThing;
```
#### 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:
```js
function doThing(message) { return message + ' a thing'; }
module.exports = doThing; // Omission of object wrapper
```
Usage of preval:
```js
const doThing = preval.require('./doDigest.js');
```
Generated code:
```js
var doThing = "undefined a thing";
```
#### 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 the `README.md` that illustrates how this is done.
Contributor guide
Research direction
Start by reproducing the direct-function export example from the issue and trace the module-loading path used by preval.require. Read README.md for the existing usage guidance and examples. Done means direct function exports no longer produce the shown undefined result, with the supported behavior documented in README.md.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- babel, javascript
- Domain
- build-system, tooling
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100