Browse Source

support async transformers (closes #260)

better-aggressive
Rich-Harris 9 years ago
parent
commit
cabc4ee097
  1. 35
      src/utils/transform.js
  2. 24
      test/function/transformer-async/_config.js
  3. 1
      test/function/transformer-async/main.js

35
src/utils/transform.js

@ -1,3 +1,5 @@
import Promise from 'es6-promise/lib/es6-promise/promise.js';
export default function transform ( source, id, transformers ) {
let sourceMapChain = [];
@ -11,24 +13,27 @@ export default function transform ( source, id, transformers ) {
let originalCode = source.code;
let ast = source.ast;
let code = transformers.reduce( ( previous, transformer ) => {
let result = transformer( previous, id );
return transformers.reduce( ( promise, transformer ) => {
return promise.then( previous => {
return Promise.resolve( transformer( previous, id ) ).then( result => {
if ( result == null ) return previous;
if ( result == null ) return previous;
if ( typeof result === 'string' ) {
result = {
code: result,
ast: null,
map: null
};
}
if ( typeof result === 'string' ) {
result = {
code: result,
ast: null,
map: null
};
}
sourceMapChain.push( result.map );
ast = result.ast;
sourceMapChain.push( result.map );
ast = result.ast;
return result.code;
});
});
return result.code;
}, source.code );
}, Promise.resolve( source.code ) )
return { code, originalCode, ast, sourceMapChain };
.then( code => ({ code, originalCode, ast, sourceMapChain }) );
}

24
test/function/transformer-async/_config.js

@ -0,0 +1,24 @@
var Promise = require( 'es6-promise' ).Promise;
module.exports = {
description: 'transformers can be asynchronous',
options: {
plugins: [
{
transform: function ( code ) {
return Promise.resolve( code.replace( 'x', 1 ) );
}
},
{
transform: function ( code ) {
return code.replace( '1', 2 );
}
},
{
transform: function ( code ) {
return Promise.resolve( code.replace( '2', 3 ) );
}
}
]
}
};

1
test/function/transformer-async/main.js

@ -0,0 +1 @@
assert.equal( x, 3 );
Loading…
Cancel
Save