Macros are a mechanism for running JavaScript functions at bundle-time. The value returned from these functions or variables are directly inlined into your bundle.
npm i -D unplugin-macros
Vite
// vite.config.ts
import Macros from 'unplugin-macros/vite'
export default defineConfig({
plugins: [Macros()],
})
Rollup
// rollup.config.js
import Macros from 'unplugin-macros/rollup'
export default {
plugins: [Macros()],
}
esbuild
// esbuild.config.js
import { build } from 'esbuild'
build({
plugins: [require('unplugin-macros/esbuild')()],
})
Webpack
// webpack.config.js
module.exports = {
/* ... */
plugins: [require('unplugin-macros/webpack')()],
}
Vue CLI
// vue.config.js
module.exports = {
configureWebpack: {
plugins: [require('unplugin-macros/webpack')()],
},
}
// main.js
import { getRandom, buildTime } from './macros' assert { type: 'macro' }
getRandom() // Will be replaced with a random number at build time
buildTime // Will be replaced with the timestamp at the build time
// macros.js
export function getRandom() {
return Math.random()
}
export const buildTime = Date.now()
See more in Bun Macros.
Thanks to Bun Macros.