Skip to content

Instantly share code, notes, and snippets.

@toolness
Created November 19, 2019 13:30
Show Gist options
  • Save toolness/75cf3c2e31ab396e6c8256516142aa7d to your computer and use it in GitHub Desktop.
Save toolness/75cf3c2e31ab396e6c8256516142aa7d to your computer and use it in GitHub Desktop.
Script to load a CRA app's babel config and run it w/ an additional example plugin.
//@ts-check
// This file can be dropped into the root of a project created
// via CRA w/ typescript support, e.g.:
//
// yarn create react-app cra-babel-fun --typescript
//
// It's just a proof-of-concept that shows how we can load
// the app's babel config and add a Babel plugin that executes
// before everything else.
//
// Make sure you add `"checkJs": true` to your `tsconfig.json` so
// this file gets type-checked and provides autocompletions on
// supported editors like VSCode.
const babel = require('@babel/core');
// We need to set either NODE_ENV or BABEL_ENV, or else
// babel-preset-react-app will throw an error telling us
// to set one of them.
process.env.BABEL_ENV = 'development';
/**
* Our example plugin. It just turns any JSX tags into
* `<strong>` and emits stuff to the console, as a proof-of-concept.
*
* @param babel {import("@babel/core")}
* @returns {import("@babel/core").PluginObj}
*/
function boopPlugin(babel) {
return {
pre() {
console.log("PRE!!!");
},
post() {
console.log("POST!!!!");
},
visitor: {
JSXOpeningElement(path) {
if (babel.types.isJSXIdentifier(path.node.name)) {
console.log(`JSX OPEN ${path.node.name.name}!`);
path.node.name = babel.types.jsxIdentifier('strong');
}
},
JSXClosingElement(path) {
if (babel.types.isJSXIdentifier(path.node.name)) {
console.log(`JSX CLOSE ${path.node.name.name}!`);
path.node.name = babel.types.jsxIdentifier('strong');
}
}
}
};
}
babel.transform('const k: JSX.Element = <p>boop</p>;', {
filename: 'example.tsx',
presets: ['babel-preset-react-app'],
plugins: [boopPlugin],
}, (err, result) => {
if (err) {
throw err;
}
console.log("FINAL TRANSFORMED CODE:\n\n", result.code);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment