README
babel-plugin-inline-constants
Babel plugin to inline constants in code. This is useful because gzip likes repeated patterns (such as using magic numbers or strings multiple times), whereas looking things up in objects is easier to develop with. “Constants” here are specific files that are imported or required which contain primitives (numbers, strings, booleans, null).
Install
This package is ESM only: Node 12+ is needed to use it and it must be import
ed
instead of require
d.
npm:
npm install babel-plugin-inline-constants
Use
First, this plugin must be configured with a pattern
, so in a .babelrc
, do:
{
"plugins": [["babel-plugin-inline-constants", {"modules": "./math"}]]
}
Then, a CJS example is as follows, math.js
:
exports.pi = 3.14
example.js
:
var math = require('./math')
console.log('one pi:', math.pi)
console.log('two pi:', 2 * math.pi)
console.log('pi pi:', math.pi * math.pi)
Now running Babel (with @babel/cli
and @babel/core
installed):
babel example.js
Yields:
console.log('one pi:', 3.14);
console.log('two pi:', 2 * 3.14);
console.log('pi pi:', 3.14 * 3.14);
Or with ESM (which requires extensions):
{
"plugins": [["babel-plugin-inline-constants", {"modules": "./math.js"}]]
}
math.js
:
export const pi = 3.14
example.js
:
import {pi} from './math.js'
console.log('one pi:', pi)
console.log('two pi:', 2 * pi)
console.log('pi pi:', pi * pi)
Then running Babel:
babel example.js
Yields the same as above.
API
This package exports no identifiers. There is only a default export.
babel-plugin-inline-constants
This is a Babel plugin. See its documentation on how to use Babel plugins.
This plugin must be configured with a modules
array.
Values in this array are the same as the x
in require(x)
or import y from x
, and resolve from the CWD (current working directory) that babel is
running in.
When these modules are then used, their values are then inlined.
So, if you are going to inline a file from node_modules
such as
charcodes
, you can use modules: ['charcodes']
.
Modules to be inlined are evaluated with Node, so only use this plugin if you completely trust your code.
To ignore the error when modules cannot be found, set ignoreModuleNotFound
to
true
.
Notes
- ESM (
import
) and CJS (require
) are supported - Modules to be inlined must be defined in
modules
- PRs welcome to make this rather experimental project better!
Related
babel-plugin-undebug
— Removedebug