{"id":12866,"library":"babel-plugin-preval","title":"Babel Plugin Preval","description":"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.","status":"maintenance","version":"5.1.0","language":"javascript","source_language":"en","source_url":"https://github.com/kentcdodds/babel-plugin-preval","tags":["javascript","babel","babel-plugin","eval","precompile","babel-plugin-macros","typescript"],"install":[{"cmd":"npm install babel-plugin-preval","lang":"bash","label":"npm"},{"cmd":"yarn add babel-plugin-preval","lang":"bash","label":"yarn"},{"cmd":"pnpm add babel-plugin-preval","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required as a peer dependency for any Babel plugin, as it integrates into the Babel compilation process.","package":"@babel/core","optional":false},{"reason":"Often 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.","package":"babel-plugin-macros","optional":true}],"imports":[{"note":"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.","wrong":"import prevalPlugin from 'babel-plugin-preval'; // Not for direct import in application code","symbol":"babel-plugin-preval (as a plugin)","correct":"// In babel.config.js or .babelrc\nmodule.exports = {\n  plugins: ['babel-plugin-preval'],\n};"},{"note":"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.","wrong":"import { preval } from 'babel-plugin-preval';\nconst staticValue = preval`...`; // 'preval' is not a direct importable JavaScript function","symbol":"preval (template tag)","correct":"const staticValue = preval`module.exports = 1 + 1`;"},{"note":"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.","wrong":"const buildTimeData = require('babel-plugin-preval').require('./config-generator.js'); // Incorrect module access","symbol":"preval.require","correct":"const buildTimeData = preval.require('./config-generator.js');"},{"note":"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.","wrong":"import precomputedValue from 'babel-plugin-preval!./constants.js'; // Not a webpack-style loader syntax","symbol":"/* preval */ (import comment)","correct":"import precomputedValue from /* preval */ './constants.js';"}],"quickstart":{"code":"/*\n  To run this example:\n  1. Install dependencies: npm install --save-dev @babel/core @babel/cli babel-plugin-preval\n  2. Create a 'babel.config.js' in your project root:\n     module.exports = {\n       plugins: ['babel-plugin-preval'],\n     };\n  3. Create a file named 'greeting.txt' in the same directory as this script:\n     Hello from Preval!\n  4. Create a file named 'preval-data.js' in the same directory as this script:\n     module.exports = { message: 'This data was pre-evaluated at build time!' };\n  5. Run Babel to transpile: npx babel your-script.ts --out-file compiled-script.js\n  6. Run the compiled script: node compiled-script.js\n*/\n\n// This code demonstrates using preval to read a file at build-time.\nconst greeting = preval`\n  const fs = require('fs');\n  const path = require('path');\n  // Using require.resolve and __dirname ensures correct path resolution during build\n  module.exports = fs.readFileSync(path.resolve(__dirname, './greeting.txt'), 'utf8');\n`;\n\n// This code demonstrates using preval.require to evaluate a JavaScript module at build-time.\nconst dynamicData = preval.require('./preval-data.js');\n\nconsole.log('Pre-evaluated greeting:', greeting);\nconsole.log('Pre-evaluated dynamic data:', dynamicData);\n\n// Expected output of the compiled and run script:\n// Pre-evaluated greeting: Hello from Preval!\n// Pre-evaluated dynamic data: { message: 'This data was pre-evaluated at build time!' }","lang":"typescript","description":"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."},"warnings":[{"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.","message":"The 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.","severity":"breaking","affected_versions":">=4.0.0"},{"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`.","message":"Code 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.","severity":"breaking","affected_versions":">=3.0.0"},{"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.","message":"All 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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"The 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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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.","message":"When 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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"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'.","cause":"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`.","error":"ReferenceError: preval is not defined"},{"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.","cause":"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.","error":"SyntaxError: Unexpected token 'import'"},{"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.","cause":"The JavaScript code provided to `preval` attempts to use asynchronous operations (e.g., `await`, Promises, non-blocking callbacks for I/O).","error":"Error: Preval code must run synchronously."},{"fix":"Ensure your Babel configuration correctly defines `plugins` as an array, even if it contains only one plugin, e.g., `plugins: ['babel-plugin-preval']`.","cause":"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.","error":"The 'plugins' config option must be an array"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":null}