Skip to content
154
3

unplugin-macros npm jsr

Unit Test

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.

Installation

bash
# npm
npm i -D unplugin-macros

# jsr
npx jsr add -D @unplugin/macros
Vite
ts
// vite.config.ts
import Macros from 'unplugin-macros/vite'

export default defineConfig({
  plugins: [Macros()],
})
Rollup
ts
// rollup.config.js
import Macros from 'unplugin-macros/rollup'

export default {
  plugins: [Macros()],
}
esbuild

Requires esbuild >= 0.15

ts
// esbuild.config.js
import { build } from 'esbuild'

build({
  plugins: [require('unplugin-macros/esbuild')()],
})
Webpack
ts
// webpack.config.js
module.exports = {
  /* ... */
  plugins: [require('unplugin-macros/webpack')()],
}

Usage

js
// main.js
import { buildTime, getRandom } from './macros' with { type: 'macro' }

getRandom() // Will be replaced with a random number at build time
buildTime // Will be replaced with the timestamp at the build time
js
// macros.js
export function getRandom() {
  return Math.random()
}
export const buildTime = Date.now()

See more in Bun Macros.

TypeScript

Import Attributes syntax is supported in TypeScript >= 5.3, but you can replace with keyword with assert, which is supported in TypeScript >= 4.5.

ESLint

ESLint is not supported Import Attributes syntax yet, but you can use @babel/eslint-parser or @typescript-eslint/parser.

js
// eslint.config.js
import parser from '@babel/eslint-parser'

export default [
  {
    // ...
    languageOptions: {
      parser,
      parserOptions: {
        requireConfigFile: false,
        babelOptions: { parserOpts: { plugins: ['importAttributes'] } },
      },
    },
  },
]

Options

Refer to docs.

Thanks

Thanks to Bun Macros.

Sponsors

License

MIT License © 2023-PRESENT 三咲智子

Released under the MIT License.