Skip to content

Commit

Permalink
Add babel transform to deconstruct Wonka's pipe (#419)
Browse files Browse the repository at this point in the history
* Add babel transform to deconstruct Wonka's pipe

* Add tracking for actual import alias

* Fix pipeExpression order

This imitates Wonka's pipe algo so that it's easier
to follow. Also the previous one was incorrect
  • Loading branch information
kitten authored Sep 6, 2019
1 parent 5102c6c commit 051fd77
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 2 deletions.
6 changes: 4 additions & 2 deletions rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import buble from 'rollup-plugin-buble';
import babel from 'rollup-plugin-babel';
import replace from 'rollup-plugin-replace';
import { terser } from 'rollup-plugin-terser';
import transformPipe from './scripts/transform-pipe';

const pkgInfo = require('./package.json');
const external = ['dns', 'fs', 'path', 'url'];
Expand Down Expand Up @@ -119,8 +120,9 @@ const makePlugins = (isProduction = false) => [
exclude: 'node_modules/**',
presets: [],
plugins: [
['babel-plugin-closure-elimination', {}],
['@babel/plugin-transform-object-assign', {}],
transformPipe,
'babel-plugin-closure-elimination',
'@babel/plugin-transform-object-assign',
['@babel/plugin-transform-react-jsx', {
pragma: 'React.createElement',
pragmaFrag: 'React.Fragment',
Expand Down
44 changes: 44 additions & 0 deletions scripts/transform-pipe.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
const pipeExpression = (t, pipeline) => {
let x = pipeline[0];
for (let i = 1; i < pipeline.length; i++)
x = t.callExpression(pipeline[i], [x]);
return x;
};

const pipePlugin = ({ types: t }) => ({
visitor: {
ImportDeclaration(path, state) {
if (path.node.source.value === 'wonka') {
const { specifiers } = path.node;
const pipeSpecifierIndex = specifiers.findIndex(spec => {
return spec.imported.name === 'pipe';
});

if (pipeSpecifierIndex > -1) {
const pipeSpecifier = specifiers[pipeSpecifierIndex];
state.pipeName = pipeSpecifier.local.name;
if (specifiers.length > 1) {
path.node.specifiers.splice(pipeSpecifierIndex, 1);
} else {
path.remove();
}
}
}
},
CallExpression(path, state) {
if (state.pipeName) {
const callee = path.node.callee;
const args = path.node.arguments;
if (callee.name !== state.pipeName) {
return;
} else if (args.length === 0) {
path.replaceWith(t.identifier('undefined'));
} else {
path.replaceWith(pipeExpression(t, args));
}
}
}
}
});

export default pipePlugin;

0 comments on commit 051fd77

Please sign in to comment.