Created
May 7, 2018 23:54
-
-
Save mlrawlings/288c007eab1d3e65ebe8d4786e1f777e to your computer and use it in GitHub Desktop.
Prevalify
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const path = require('path'); | |
const { createMacro } = require("babel-plugin-macros"); | |
const objectToAST = require("babel-plugin-preval/src/object-to-ast"); // https://github.com/kentcdodds/babel-plugin-preval/blob/b6eeba02ee93d425cc673ffc23dc62375d0416e5/src/object-to-ast.js | |
export default fn => | |
createMacro(({ references, state, babel }) => { | |
references.default.forEach(referencePath => { | |
if (referencePath.parentPath.type === "CallExpression") { | |
const __filename = state.file.opts.filename; | |
const __dirname = path.dirname(__filename); | |
const callExpressionPath = referencePath.parentPath; | |
const args = callExpressionPath | |
.get("arguments") | |
.map(arg => arg.evaluate().value); | |
const value = fn.apply({ __filename, __dirname }, args); | |
referencePath.parentPath.replaceWith(objectToAST(value)); | |
} else { | |
const source = referencePath | |
.findParent(babel.types.isExpression) | |
.getSource(); | |
throw new Error( | |
`This is not supported: \`${source}\`. Please use a function call` | |
); | |
} | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
const path = require('path'); | |
const prevalify = require('prevalify'); | |
const readFile = (filepath) => { | |
const resolvedPath = path.resolve(this.__dirname || process.cwd(), filepath); | |
return fs.readFileSync(resolvedPath, { encoding: 'utf-8' }); | |
}; | |
export default prevalify(readFile); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const readFile = require('read-file/macro'); | |
const fileContents = readFile('./README.md'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment