Last active
December 9, 2018 02:41
-
-
Save chardos/4f7df977f8ce4ca9a88d87ad7b6005fb to your computer and use it in GitHub Desktop.
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
// transform.js | |
const fs = require('fs'); | |
const parser = require('@babel/parser').parse; | |
const traverse = require('@babel/traverse').default; | |
const generate = require('@babel/generator').default; | |
const t = require("@babel/types"); | |
const prettier = require('prettier'); | |
const fileLocation = './reducers.js'; | |
const file = fs.readFileSync(fileLocation).toString(); | |
const ast = parser(file, {sourceType: 'module'}); | |
const REDUCER_NAME = 'mice'; | |
let lastImport; | |
let properties; | |
// Traverse the AST to find the nodes we need. | |
traverse(ast, { | |
ImportDeclaration(path) { | |
lastImport = path; | |
}, | |
ObjectExpression(path) { | |
properties = path.parent.declaration.properties | |
}, | |
}) | |
// add import to AST | |
const importCode = `import ${REDUCER_NAME} from './${REDUCER_NAME}'`; | |
lastImport.insertAfter(parser(importCode, {sourceType: 'module'})); | |
// add export to AST | |
const id = t.identifier(REDUCER_NAME) | |
properties.push(t.objectProperty(id, id, false, true)) | |
const newCode = generate(ast).code; | |
const prettifiedCode = prettier.format(newCode, { parser: 'babylon' }) | |
fs.writeFile('transformed.js', prettifiedCode, (err) => { | |
if (err) throw new Error(`addToReducerIndex.js write error: ${err}`) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment