Skip to content

HTML IIFE Script Plugin

A staticbolt plugin that wraps inline <script> tags in an Immediately Invoked Function Expression (IIFE). Every variable declared in the script stays out of the global scope and cannot clash with a name from another script on the page.

Installation

The plugin ships as part of @staticbolt/core. You do not need to install anything else.

Usage

In your .staticbolt.ts configuration file:

import { defineConfig } from "@staticbolt/core";
import { htmlIifeScriptPlugin } from "@staticbolt/core/plugins";
export default defineConfig({
plugins: [htmlIifeScriptPlugin()],
});

Wrapping a script in an IIFE

Add the iife attribute to any inline <script> tag. The plugin wraps the script's content in an IIFE and removes the iife attribute from the output.

<script iife>
const message = "Hello";
console.log(message);
</script>
<!-- Output -->
<script>
(() => {
const message = "Hello";
console.log(message);
})();
</script>

This only works with inline scripts. A script with a src attribute cannot be wrapped, because the plugin does not have its content at this stage. For external scripts, use htmlBundleScriptPlugin with its own iife attribute instead.

The iife attribute is meant for global scripts only. On a type="module" script it produces a warning, since module scripts are already scoped by default and wrapping them in an IIFE serves no purpose.

Plugin Options

iifeAttribute

  • Type: string
  • Default: "iife"

The attribute name that marks an inline script tag for IIFE wrapping.

htmlIifeScriptPlugin({
iifeAttribute: "scoped",
});