Given the following:
require('babel-core').transform('3').code
Is there a way to get this to return 3
(an expression) instead of 3;
(a statement)?
I've tried:
(3)
, but that also was transformed into 3;
.minified: true
, which claims to remove the trailing semicolon but doesn't actually seem to do anything.Right now I'm using .replace(/;$/, '')
, which works but seems absurd and error-prone.
You can use babel-standalone to transpile ES6 to ES5 in a browser environment. You just need to load the “babel-standalone” in your script as highlighted below and write the script you want to transpile, in script tag with type “text/babel” or “text/jsx”. Babel will automatically compile and execute the script.
Simply add a "scripts" field to your package. json and put the babel command inside there as build . This will run Babel the same way as before and the output will be present in lib directory, only now we are using a local copy. Alternatively, you can reference the babel cli inside of node_modules .
@babel/preset-env is a smart preset that allows you to use the latest JavaScript without needing to micromanage which syntax transforms (and optionally, browser polyfills) are needed by your target environment(s). This both makes your life easier and JavaScript bundles smaller!
@loganfsmyth provided the missing link on BabelJS.slack -- parserOpts.allowReturnOutsideFunction
. Here's 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 input script looks a bit funny just because of how I generated it, but you can see that it transformed those arrow expressions into regular functions and the whole thing is still an expression.
N.B. you may want to modify that last line to something like
let code = `(function(){${transform.code}})()`;
depending on your needs. I needed mine to be return
ed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With