vite-plugin-iife
v1.1.6
Published
Vite plugin for simple IIFE-compiled script imports.
Downloads
28
Maintainers
Readme
vite-plugin-iife
Vite plugin for simple IIFE-compiled script imports.
Overview
Sometimes you need a small snippet of code to run in a specific place at at a specific time during a page's loading process to achieve a specific effect or prevent the dreaded FOUC.
Running scripts as modules is great, but by design they are unavoidably executed with an implicit defer
, and build systems can make it tricky to get a single chunk of code to behave differently.
This plugin lets you write scripts to be inlined using either JavaScript or TypeScript, and get a minified JavaScript IIFE
snippet of code via an import
statement, which makes it easy to integrate with static site generators:
import inlineIifeSnippet from './some-script.ts?iife'
// Logs the raw IIFE-compiled code from some-script.ts:
console.log(inlineIifeSnippet)
Installation
1. Install the plugin package
Assuming you're starting with a Vite project of some flavor:
npm install --save-dev vite-plugin-iife
2. Add the plugin to your vite.config
file
// vite.config.ts
import iife from 'vite-plugin-iife'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [iife()],
})
3. Configure TypeScript
Skip this step if you're using plain JavaScript.
Add the extension declarations to your types in tsconfig.json:
{
"compilerOptions": {
"types": ["vite-plugin-iife/ext"]
}
}
Alternately, you can add a triple-slash package dependency directive to your global types file (e.g. env.d.ts
or similar):
/// <reference types="vite-plugin-iife/ext" />
This step should take care of errors like:
Cannot find module './test-script.ts?iife' or its corresponding type declarations.ts(2307)
Usage
IIFE imports
Append ?iife
to any script import string to receive the IIFE-compiled code as a default export string:
// Imported as an IIFE-compiled string
// Embed it in a <script> tag somewhere, etc.
import iifeSnippet from './some-script.ts?iife'
// Imported normally
import snippet from './some-script.ts'
Since there's no code splitting or externalization of dependencies, vite-plugin-iife
is only recommended for small and relatively self-contained scripts. The verbose
option can help you keep tabs on the output size during development.
Plugin options
The plugin accepts a few options in its initialization function in your vite.config
file. The options object type is exported as IifePluginOptions
.
| Key | Type | Description | Default |
| --------- | ------------------------- | ------------------------------------------------------------------- | ------- |
| minify
| true \| false \| 'auto'
| Minify output. The 'auto' value only minifies on production builds. | 'auto' |
| verbose
| boolean
| Log information to the console. | false
|
Maintainers
Contributing
Issues and pull requests are welcome.
License
MIT © Eric Mika