2017-05-02 24 views
0

如何在sweet.js生成的输出中插入任意字符串?将任意字符串插入sweet.js输出

这对于以编程方式处理字符串因各种条件而不同的情况非常有用。

例如,在下面代码的第25行中,我想插入一个字符串作为结果。

sweet.js代码:

import { produceNormalParams } from './abc/produceNormalParams' 
    import { produceParamChecks } from './abc/produceParamChecks' 
    import { produceInnerChecks } from './abc/produceInnerChecks' 

    syntax function = function(ctx) { 
     let funcName = ctx.next().value; 
     let funcParams = ctx.next().value; 
     let funcBody = ctx.next().value; 

     //produce the normal params array 
     var normalParams = produceNormalParams(funcParams) 

     //produce the checks 
     var paramChecks = produceParamChecks(funcParams) 

     //produce the original funcBody code 
     var inner = produceInnerChecks(funcParams) 

     var someArbitraryString = "console.log('hey')" 

     //put them together as the final result 
     var result = #`function ${funcName} ${normalParams} { 
      ${someArbitraryString} 
      ${paramChecks} 
      ${inner} 
     }` 

     return result 
    } 

例输入:

module.exports = multiply 

    function multiply(a:array,b,c:array) { 
     return a * c 
    } 

输出示例:

// Example Output 
    module.exports = multiply; 
    function multiply(a_31, b_32, c_33) { 
     console.log('hey') 
     if (Object.prototype.toString.call(a_31) !== "[object Array]") throw new Error("Must be array:" + a_31); 
     if (Object.prototype.toString.call(c_33) !== "[object Array]") throw new Error("Must be array:" + c_33); 
     return a_31 * c_33; 
    } 

回答

1

虽然你不能插入任意字符串到一个语法模板,你可以插入其他语法模板。

import { produceNormalParams } from './abc/produceNormalParams' for syntax; 
import { produceParamChecks } from './abc/produceParamChecks' for syntax; 
import { produceInnerChecks } from './abc/produceInnerChecks' for syntax; 

syntax function = function(ctx) { 
    let funcName = ctx.next().value; 
    let funcParams = ctx.next().value; 
    let funcBody = ctx.next().value; 

    //produce the normal params array 
    var normalParams = produceNormalParams(funcParams); 

    //produce the checks 
    var paramChecks = produceParamChecks(funcParams); 

    //produce the original funcBody code 
    var inner = produceInnerChecks(funcParams); 

    var someArbitrarySyntax = #`console.log('hey')`; 

    //put them together as the final result 
    var result = #`function ${funcName} ${normalParams} { 
     ${someArbitrarySyntax} 
     ${paramChecks} 
     ${inner} 
    }`; 

    return result 
} 

注意尾随导入语句的for syntax。这些对于导入在编译期间可用是必需的。

+0

这个例子起作用。然而,是否有可能获得以编程方式生成的现有字符串...例如函数getString(){返回'abcdef'}并将其转换为语法 我基本上想将某些参数传递给库使库返回字符串,然后插入该字符串 –

+0

不在当前时间。如果它是你的库,并且你没有在任何其他上下文中使用它,你可以让它返回语法模板而不是字符串。 –