Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add babel transform to deconstruct Wonka's pipe #419

Merged
merged 3 commits into from
Sep 6, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;