Compile time code replacement for babel similar to Webpack's DefinePlugin
$ npm install --save-dev babel-plugin-transform-define
.babelrc
{
"plugins": [
["transform-define", {
"process.env.NODE_ENV": "production",
"typeof window": "object"
}]
]
}
.babelrc.js
// E.g., any dynamic logic with JS, environment variables, etc.
const overrides = require("./another-path.js");
module.exports = {
plugins: [
["transform-define", {
"process.env.NODE_ENV": "production",
"typeof window": "object",
...overrides
}]
]
};
babel-plugin-transform-define
can transform certain types of code as a babel transformation.
.babelrc
{
"plugins": [
["transform-define", {
"VERSION": "1.0.0",
}]
]
}
Source Code
VERSION;
window.__MY_COMPANY__ = {
version: VERSION
};
Output Code
"1.0.0";
window.__MY_COMPANY__ = {
version: "1.0.0"
};
.babelrc
{
"plugins": [
["transform-define", {
"process.env.NODE_ENV": "production"
}]
]
}
Source Code
if (process.env.NODE_ENV === "production") {
console.log(true);
}
Output Code
if (true) {
console.log(true);
}
.babelrc
{
"plugins": [
["transform-define", {
"typeof window": "object"
}]
]
}
Source Code
typeof window;
typeof window === "object";
Output Code
'object';
true;