Registry / devops / babel-plugin-preval

babel-plugin-preval

JSON →
library5.1.0jsnpmunverified

babel-plugin-preval is a Babel plugin designed to pre-evaluate JavaScript code at build-time, effectively replacing dynamic runtime computations with static, precomputed values. Its current stable version is 5.1.0. While the last major release was in 2022, the package continues to be used, with discussions and related macro packages still active in the community. This plugin allows for tasks like reading file systems or performing complex calculations during the build process, which are typically impossible or inefficient at runtime, especially in browser environments. Unlike generic build-time evaluators, preval integrates directly into the Babel compilation pipeline and provides multiple mechanisms for invocation, including template literal tags, `preval.require` calls, and `/* preval */` import comments. A crucial distinction is that the code executed by `preval` runs directly in a Node.js environment, is not sandboxed, and is *not* automatically transpiled by Babel, meaning it must be compatible with the Node.js version used for the build process.

npm install babel-plugin-preval
INSTALL
IMPORT
SIG · BABEL-PLUGIN-PREVA
B
babel-plugin-preval
devopsjavascriptv5.1.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

babel-plugin-preval (as a plugin)
// In babel.config.js or .babelrc module.exports = { plugins: ['babel-plugin-preval'], };
import prevalPlugin from 'babel-plugin-preval'; // Not for direct import in application code
This is how the plugin itself is configured within your Babel setup. The plugin is not imported into application code for direct runtime use, but rather transforms code during the build process.
preval (template tag)
const staticValue = preval`module.exports = 1 + 1`;
import { preval } from 'babel-plugin-preval'; const staticValue = preval`...`; // 'preval' is not a direct importable JavaScript function
The `preval` template tag is a special syntax processed by the Babel plugin at build-time. It is not an imported JavaScript function or variable, nor does it require a direct `import` statement in your source files to be recognized by the plugin.
preval.require
const buildTimeData = preval.require('./config-generator.js');
const buildTimeData = require('babel-plugin-preval').require('./config-generator.js'); // Incorrect module access
This pattern is recognized and processed by `babel-plugin-preval` to execute the specified module at build-time, replacing the call with the module's export. The `preval` global is implicitly provided by the plugin during transformation.
/* preval */ (import comment)
import precomputedValue from /* preval */ './constants.js';
import precomputedValue from 'babel-plugin-preval!./constants.js'; // Not a webpack-style loader syntax
The `/* preval */` comment instructs the plugin to pre-evaluate the imported module, embedding its exports directly into the bundle. Note that the imported module itself is not transpiled by Babel before execution within Preval.

Demonstrates `babel-plugin-preval` reading a file and evaluating a module at build-time, embedding static results into the output bundle. This requires a Babel setup with the plugin configured.

/* To run this example: 1. Install dependencies: npm install --save-dev @babel/core @babel/cli babel-plugin-preval 2. Create a 'babel.config.js' in your project root: module.exports = { plugins: ['babel-plugin-preval'], }; 3. Create a file named 'greeting.txt' in the same directory as this script: Hello from Preval! 4. Create a file named 'preval-data.js' in the same directory as this script: module.exports = { message: 'This data was pre-evaluated at build time!' }; 5. Run Babel to transpile: npx babel your-script.ts --out-file compiled-script.js 6. Run the compiled script: node compiled-script.js */ // This code demonstrates using preval to read a file at build-time. const greeting = preval` const fs = require('fs'); const path = require('path'); // Using require.resolve and __dirname ensures correct path resolution during build module.exports = fs.readFileSync(path.resolve(__dirname, './greeting.txt'), 'utf8'); `; // This code demonstrates using preval.require to evaluate a JavaScript module at build-time. const dynamicData = preval.require('./preval-data.js'); console.log('Pre-evaluated greeting:', greeting); console.log('Pre-evaluated dynamic data:', dynamicData); // Expected output of the compiled and run script: // Pre-evaluated greeting: Hello from Preval! // Pre-evaluated dynamic data: { message: 'This data was pre-evaluated at build time!' }
Debug
Known issues
breakingThe minimum Node.js version requirement for `babel-plugin-preval` has progressively increased. Version 4.0.0 required Node.js >= 8, and version 5.0.0 further increased this to Node.js >= 10. Using older Node.js versions will result in compilation failures.
fix
Ensure your build environment uses Node.js version 10 or newer. It is recommended to use the latest LTS Node.js version for compatibility.
affects: >=4.0.0
breakingCode executed by `babel-plugin-preval` is no longer automatically transpiled by Babel before execution within the plugin. This means any JavaScript syntax or features used in prevaled code (e.g., inside template tags or `preval.require` files) must be natively supported by the Node.js version running the build, or be pre-transpiled.
fix
Update prevaled code to use syntax compatible with your Node.js build environment (e.g., CommonJS modules instead of ESM, older JavaScript features). If modern syntax is required, pre-transpile the prevaled code using a separate Babel pass or ensure your Node.js version supports it. For instance, do not use `import/export` syntax within `preval` code blocks, stick to `require()` and `module.exports`.
affects: >=3.0.0
gotchaAll code executed by `babel-plugin-preval` runs directly in a Node.js environment without sandboxing. This means it has full access to the file system and network, and any malicious code could potentially compromise your build environment.
fix
Only preval code from trusted sources and carefully review any third-party code that might be evaluated by the plugin. Treat prevaled code with the same security considerations as any Node.js script.
affects: >=1.0.0
gotchaThe code evaluated by `babel-plugin-preval` *must* run synchronously. Asynchronous operations (like Promises, `async/await`, or non-blocking I/O) are not supported and will result in errors or unexpected behavior during the build process.
fix
Refactor prevaled code to exclusively use synchronous Node.js APIs (e.g., `fs.readFileSync` instead of `fs.readFile`). Ensure all operations complete before `module.exports` is assigned a value.
affects: >=1.0.0
gotchaWhen using `babel-plugin-preval`, changes to the content of files referenced by `preval` might not always trigger a recompilation during development, especially if the `preval` call itself (e.g., the template literal string) hasn't changed. This can lead to stale pre-evaluated values.
fix
To force a recompile, you may need to touch the file containing the `preval` call or clear your Babel/Webpack cache. Some build systems might require specific configurations to properly track dependencies for `preval` files.
affects: >=1.0.0
Errors
Common errors & fixes
ReferenceError: preval is not defined
The `preval` template tag or `preval.require` was used in code without `babel-plugin-preval` being correctly configured in Babel, or without `preval.macro` and `babel-plugin-macros`.
fix
Ensure 'babel-plugin-preval' is listed in the `plugins` array of your `.babelrc` or `babel.config.js` file. If using `preval.macro`, ensure `babel-plugin-macros` is configured and you are importing `preval` from 'preval.macro'.
SyntaxError: Unexpected token 'import'
The code being pre-evaluated by `preval` (e.g., inside the template literal or a `preval.require`'d file) is using ES module `import`/`export` syntax, which is not natively supported by the Node.js version running the build process, and is not transpiled by Preval itself.
fix
Rewrite the prevaled code to use CommonJS `require()` and `module.exports` syntax. Ensure all code executed by `preval` is compatible with the Node.js version you are using to run Babel, or pre-transpile that specific code.
Error: Preval code must run synchronously.
The JavaScript code provided to `preval` attempts to use asynchronous operations (e.g., `await`, Promises, non-blocking callbacks for I/O).
fix
Refactor the prevaled code to be entirely synchronous. For file system operations, use synchronous methods like `fs.readFileSync` instead of `fs.readFile`. Avoid Promises and `async/await` within prevaled blocks.
The 'plugins' config option must be an array
The Babel configuration file (`.babelrc` or `babel.config.js`) has an incorrect format for specifying plugins, for example, providing a string directly instead of an array.
fix
Ensure your Babel configuration correctly defines `plugins` as an array, even if it contains only one plugin, e.g., `plugins: ['babel-plugin-preval']`.
Upgrade
Version history
5.1.0latest on npm
Audit
Dependencies
@babel/corerequiredRequired as a peer dependency for any Babel plugin, as it integrates into the Babel compilation process.
babel-plugin-macrosoptionalOften used in conjunction with `preval.macro` to provide a more declarative and zero-config way to use preval functionality, especially in environments like Create React App.
Agent activity
16 hits · last 30 days
node
14
OpenAI (training)
1
Resources
babel-plugin-preval — npm install babel-plugin-preval · libregistry