nuxt-define
v1.0.1
Published
One utility function for module authors to define compiler constants for all builders supported by Nuxt.
Readme
Nuxt Define
[!WARNING] This package is deprecated, copy the snippet below into your module instead.
One utility function for module authors to define compiler constants for all builders supported by Nuxt.
Supported builders:
- Vite
- Webpack
- Rspack
Replacement
Webpack and Rspack pass themselves to plugins as compiler.webpack, so the same can be done with a few lines and @nuxt/kit, without adding these builders as dev dependencies.
// src/utils.ts
import { addRspackPlugin, addWebpackPlugin, extendViteConfig } from '@nuxt/kit'
interface Compiler {
webpack: { DefinePlugin: new (define: Record<string, string>) => { apply(compiler: Compiler): void } }
}
export function addDefinePlugin(define: Record<string, string>) {
const plugin = { apply: (compiler: Compiler) => new compiler.webpack.DefinePlugin(define).apply(compiler) }
addWebpackPlugin(plugin)
addRspackPlugin(plugin)
extendViteConfig((config) => {
config.define = { ...config.define, ...define }
})
}Installation
npm i nuxt-defineUsage
// src/module.ts
import { addDefinePlugin } from 'nuxt-define'
export default defineNuxtModule({
setup() {
addDefinePlugin({
'__MY_CONSTANT__': JSON.stringify('myValue'),
'__SOME_FEATURE_FLAG__': JSON.stringify(false),
})
}
})// src/runtime/foo.ts
export function foo() {
console.log(__MY_CONSTANT__) // 'myValue'
if (__SOME_FEATURE_FLAG__) {
// expensive computation
// omitted from final build if compiler constant is false
}
}
