diff --git a/rollup.config.js b/rollup.config.js index fed9311d96..048f725d5e 100644 --- a/rollup.config.js +++ b/rollup.config.js @@ -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']; @@ -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', diff --git a/scripts/transform-pipe.js b/scripts/transform-pipe.js new file mode 100644 index 0000000000..9081f447a1 --- /dev/null +++ b/scripts/transform-pipe.js @@ -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;