unplugin-swc-macros
v0.0.4
Published
> [!NOTE] > This is a fork of [unplugin-parcel-macros](https://github.com/devongovett/unplugin-parcel-macros), but with the Parcel bundler removed (saving 200M+ disk size)
Downloads
5
Readme
unplugin-swc-macros
[!NOTE] This is a fork of unplugin-parcel-macros, but with the Parcel bundler removed (saving 200M+ disk size)
An Unplugin that lets you use Parcel's macro implementation in webpack, Vite, Rollup, esbuild, Next.js, and more.
Macros are JavaScript functions that run at build time. The value returned by a macro is inlined into the bundle in place of the original function call. This allows you to generate constants, code, and even additional assets without any custom plugins.
Macros are imported using an import attribute to indicate that they should run at build time rather than being bundled into the output. You can import any JavaScript or TypeScript module as a macro, including built-in Node modules and packages from npm.
Example
This example uses the regexgen library to generate an optimized regular expression from a set of strings at build time.
import regexgen from 'regexgen' with {type: 'macro'};
const regex = regexgen(['foobar', 'foobaz', 'foozap', 'fooza']);
console.log(regex);
This compiles to the following bundle:
console.log(/foo(?:zap?|ba[rz])/);
As you can see, the regexgen
library has been completely compiled away, and we are left with a static regular expression!
Setup
webpack
// webpack.config.js
const macros = require('unplugin-swc-macros');
module.exports = {
// ...
plugins: [
macros.webpack()
]
};
Next.js
// next.config.js
const macros = require('unplugin-swc-macros');
// Create a single instance of the plugin that's shared between server and client builds.
let plugin = macros.webpack();
module.exports = {
webpack(config) {
config.plugins.push(plugin);
return config;
}
};
Vite
// vite.config.js
import macros from 'unplugin-swc-macros';
export default {
plugins: [
macros.vite()
]
};
Rollup
// rollup.config.js
import macros from 'unplugin-swc-macros';
export default {
plugins: [
macros.rollup()
]
};
Esbuild
import {build} from 'esbuild';
import macros from 'unplugin-swc-macros';
build({
plugins: [
macros.esbuild()
]
});