This plugin allows Babel to execute ceval
functions at compile time. It can be used for any kind
of code generations that needs to happen at build time. Instead of writing complicated build scripts, you can write
those code generation logics right inside your code.
- Installation
- Usage
- API
- Examples
- Reading environment variables
- Current source directory / filename
- Version information from package.json
- Generate js code via js code
- Return string from ceval(fn: function)
- Different functions for different environments
- Reading outside variables (they must be statically evaluatable)
- Return complete objects
- Return a Promise
npm install --save-dev babel-plugin-ceval
Via .babelrc (Recommended)
.babelrc
{
"plugins": ["ceval"]
}
babel --plugins ceval script.js
Return value is used as is, it cannot return code fragments.
If it returns a string, it is expected to be a code fragment. If you need to return a string value, simply enclose it with quotations (If string contains quotations, use JSON.stringify).
// In:
var envPath = ceval('process.env.PATH');
// Out:
var envPath = '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games';
// In:
var dirname = ceval('__dirname');
var filename= ceval('__filename');
// Out:
var dirname = '/home/arash16/Projects/ceval-test';
var filename = '/home/arash16/Projects/ceval-test/test.js';
// In:
var version = ceval('require("./package.json").version');
// Out:
var version = '1.0.0';
// In:
ceval(function() {
var r = '';
for (var i=0; i<4; ++i)
r += 'console.log('+i+');';
return r;
});
// Out:
console.log(0);console.log(1);console.log(2);console.log(3);
// In:
var code = ceval(function() {
var r = '';
for (var i=0; i<3; ++i)
r += 'console.log('+i+');';
return JSON.stringify(r);
});
// Out:
var code = 'console.log(0);console.log(1);console.log(2);';
// In:
ceval(function() {
if (process.env.SERVER)
return function checker(x) {
return x>2;
};
return function checker(x) {
return x>0;
};
});
// Out:
function checker(x) {
return x > 0;
}
// In:
const X = 1, Y = 2;
ceval(function(a, b) {
return 'console.log(' + (a+b) + ');';
}, X, Y);
// Out:
const X = 1,
Y = 2;
console.log(3);
// In:
var obj = ceval(function() {
return {
regex: /abc/g,
str: 'asdas',
arr: [1,2, { x: 1}],
fn: function (a, b) {
return a + b;
}
};
});
// Out:
var obj = {
'regex': /abc/g,
'str': 'asdas',
'arr': [1, 2, {
'x': 1
}],
'fn': function (a, b) {
return a + b;
}
};
If you need to return a promise, make sure to install deasync too.
npm install --save-dev deasync
// In:
ceval(function() {
return Promise
.resolve('read from database')
.then(x => `function dyna() {
return ${JSON.stringify(x.split(' '))};
}`);
});
// Out:
function dyna() {
return ["read", "from", "database"];
}