Nuxt Compiler Constants Utility
nuxt-define is a utility package designed for Nuxt module authors to uniformly define compiler constants across all supported Nuxt builders, including Vite, Webpack, and Rspack. It abstracts away the builder-specific mechanisms for constant definition, providing a single `addDefinePlugin` function. This allows module developers to avoid adding builder-specific dev dependencies, reducing dependency noise and ensuring consistent behavior regardless of the underlying bundler chosen by the Nuxt project. The current stable version is 1.0.0, suggesting a mature initial release. As a utility, its release cadence is likely tied to Nuxt ecosystem updates or bug fixes, rather than a strict schedule. Its key differentiator is simplifying cross-builder constant definition and enabling effective dead code elimination for feature flags during the build process, leading to optimized bundles.
Common errors
-
ReferenceError: __SOME_FEATURE_FLAG__ is not defined
cause Attempting to access a compiler constant in runtime code without it being properly defined via `addDefinePlugin` in a Nuxt module, or trying to access it in a context where the build-time replacement has not occurred.fixEnsure `addDefinePlugin` is called within your Nuxt module's `setup()` function and that the constant name exactly matches. Confirm the constant is used in code processed by the Nuxt build (e.g., `src/runtime/` files). -
SyntaxError: Invalid or unexpected token (e.g., if (true,) { ... })cause A non-string value (like a boolean or number) was passed to `addDefinePlugin` without being wrapped in `JSON.stringify()`, leading to raw value substitution that breaks JavaScript syntax.fixAlways use `JSON.stringify()` for the constant values, even for booleans, numbers, or strings (e.g., `'__MY_FLAG__': JSON.stringify(true)`). -
TS2304: Cannot find name '__MY_CONSTANT__'.
cause TypeScript compiler cannot resolve the globally injected compiler constant during type checking, even if it works at runtime.fixCreate a `globals.d.ts` file in your project (e.g., `src/types/globals.d.ts`) and declare the constants: `declare const __MY_CONSTANT__: string;`.
Warnings
- gotcha Values passed to `addDefinePlugin` must be stringified using `JSON.stringify()` if they are not already strings. Forgetting this can lead to syntax errors in the bundled output, as the values are directly substituted into the code.
- gotcha Compiler constants are replaced at build time, meaning they are not dynamic runtime variables. Changes to constants require a re-build. They are also subject to dead code elimination if used in conditional statements with a falsy value (e.g., `if (__FEATURE_FLAG__)`).
- gotcha Compiler constants are not typed by default. If using TypeScript, you may need to declare them globally to avoid 'Cannot find name '__MY_CONSTANT__'' errors in your runtime code.
Install
-
npm install nuxt-define -
yarn add nuxt-define -
pnpm add nuxt-define
Imports
- addDefinePlugin
const { addDefinePlugin } = require('nuxt-define')import { addDefinePlugin } from 'nuxt-define' - __MY_CONSTANT__
console.log(global.__MY_CONSTANT__)
console.log(__MY_CONSTANT__)
Quickstart
import { defineNuxtModule } from '@nuxt/kit';
import { addDefinePlugin } from 'nuxt-define';
export default defineNuxtModule({
meta: {
name: 'my-feature-module',
configKey: 'myFeature'
},
setup(_options, _nuxt) {
// Define compiler constants that will be available globally in your runtime code
addDefinePlugin({
'__MY_MODULE_VERSION__': JSON.stringify('1.2.3'),
'__ENABLE_ANALYTICS__': JSON.stringify(true),
'__API_ENDPOINT__': JSON.stringify(process.env.API_ENDPOINT ?? 'https://api.example.com/default')
});
// Example of how these constants might be used in a runtime file (e.g., src/runtime/analytics.ts)
// if (__ENABLE_ANALYTICS__) {
// console.log(`Analytics enabled. Module version: ${__MY_MODULE_VERSION__}`);
// // initAnalytics(__API_ENDPOINT__);
// }
console.log('Nuxt module setup completed, constants defined.');
}
});