preval.macro: Build-Time Code Evaluation

5.0.0 · active · verified Tue Apr 21

preval.macro is a Babel macro designed to pre-evaluate code at build-time, embedding the results directly into the JavaScript bundle. It leverages `babel-plugin-preval` under the hood, offering a streamlined way to achieve static code evaluation without direct Babel plugin configuration, thanks to its integration with `babel-plugin-macros`. The current stable version is 5.0.0. This package is particularly useful for tasks like inlining static file contents, injecting environment variables known at build time, or pre-calculating complex values, thereby reducing runtime computations and potentially optimizing bundle size. Its release cadence is generally aligned with updates to the broader Babel ecosystem and its upstream dependencies, `babel-plugin-preval` and `babel-plugin-macros`.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use `preval.macro` to evaluate arithmetic expressions, inject environment variables, and read file contents at build-time, embedding the results directly into the output JavaScript bundle.

/*
  1. Install dependencies:
  npm install --save-dev @babel/cli @babel/core babel-plugin-macros preval.macro

  2. Create `.babelrc.js` in your project root:
  module.exports = {
    plugins: ['macros'],
  };

  3. Create `src/index.js`:
*/

import preval from 'preval.macro';

// Pre-evaluate a simple arithmetic expression during build
const sum = preval`module.exports = 10 + 20`;
console.log('The sum is:', sum); // During build, 'sum' becomes 30

// Pre-evaluate and embed an environment variable (e.g., BUILD_ID=abc)
// To see this in action, run Babel with an environment variable:
// BUILD_ID=123 babel src --out-dir dist
const buildId = preval`module.exports = process.env.BUILD_ID || 'N/A'`;
console.log('Build ID:', buildId); // 'buildId' becomes '123' at build time

// Read a file at build-time and embed its content
// Create a file `src/data.txt` with content: 'Hello Preval World!'
const fileContent = preval`
  const fs = require('fs');
  const path = require('path');
  module.exports = fs.readFileSync(path.resolve(__dirname, 'data.txt'), 'utf8');
`;
console.log('File Content:', fileContent); // 'fileContent' becomes 'Hello Preval World!'

/*
  4. Create `src/data.txt` in the same directory as `src/index.js`
     with content: `Hello Preval World!`

  5. Compile with Babel from your project root:
  BUILD_ID=123 babel src --out-dir dist

  6. Run the compiled output:
  node dist/index.js
  // Expected output:
  // The sum is: 30
  // Build ID: 123
  // File Content: Hello Preval World!
*/

view raw JSON →