How to translate expression * using babel?

Given the following:

require('babel-core').transform('3').code 

Is there a way to make this return 3 (expression) instead of 3; (instruction)?

I tried:

  • Search the Internet and various sites for the expression "babel expression", "expression babel transpile", etc.
  • Transmission (3) , but has also been converted to 3; .
  • Shaking babel's insides to figure out what is happening, but I don't know enough about how this works to figure it out.
  • Passing the minified: true option, which claims to remove the end semicolon, but actually does nothing.

Right now I am using .replace(/;$/, '') , which works, but seems absurd and error prone.

+6
source share
1 answer

@loganfsmyth provided the missing link at BabelJS.slack - parserOpts.allowReturnOutsideFunction . Here is the code I came up with:

 const babel = require('babel-core'); let script = 'return ((selector, callback) => Array.prototype.map.call(document.querySelectorAll(selector), callback))("#main table a.companylist",a => a.innerText)'; let transform = babel.transform(script, { ast: false, code: true, comments: false, compact: true, minified: true, presets: [ ['env', { targets: { browsers: ['> 1%', 'last 2 Firefox versions', 'last 2 Chrome versions', 'last 2 Edge versions', 'last 2 Safari versions', 'Firefox ESR', 'IE >= 8'], } }] ], parserOpts: { allowReturnOutsideFunction: true, } }); let code = `return function(){${transform.code}}()`; 

Output:

 return function(){"use strict";return function(selector,callback){return Array.prototype.map.call(document.querySelectorAll(selector),callback)}("#main table a.companylist",function(a){return a.innerText});}() 

My script entry looks a little funny just because of how I generated it, but you can see that it turned these arrow expressions into regular functions, and this is still an expression.

NB you can change this last line to something like

 let code = `(function(){${transform.code}})()`; 

depending on your needs. I needed my return ed.

+4
source

Source: https://habr.com/ru/post/1013805/


All Articles