Skip to content

Instantly share code, notes, and snippets.

@sebinsua
Created September 18, 2024 09:07
Show Gist options
  • Save sebinsua/4ea1e29dde50587af9e38da3fbc93f9e to your computer and use it in GitHub Desktop.
Save sebinsua/4ea1e29dde50587af9e38da3fbc93f9e to your computer and use it in GitHub Desktop.
crossorigin.plugin.ts
import type { Plugin, UserConfig } from 'vite';
type CrossOriginValue = 'anonymous' | 'use-credentials' | '';
interface CrossOriginPluginOptions {
/**
* The value to set for the crossorigin attribute.
* @default 'use-credentials'
*/
crossOriginValue?: CrossOriginValue;
}
export default function crossOriginPlugin(options: CrossOriginPluginOptions = {}): Plugin {
const crossOriginValue = options.crossOriginValue || 'use-credentials';
return {
name: 'vite-plugin-crossorigin',
config(config: UserConfig) {
config.build = config.build || {};
config.build.rollupOptions = config.build.rollupOptions || {};
config.build.rollupOptions.output = config.build.rollupOptions.output || {};
const existingManualChunks = config.build.rollupOptions.output.manualChunks;
config.build.rollupOptions.output.manualChunks = (id: string, api: any) => {
if (id === '\0vite/preload-helper') {
return 'preload-helper';
}
if (typeof existingManualChunks === 'function') {
return existingManualChunks(id, api);
}
};
return config;
},
transformIndexHtml(html: string) {
// Replace existing crossorigin attributes
return html.replace(/crossorigin(="[^"]*")?/g, `crossorigin="${crossOriginValue}"`);
},
generateBundle(_, bundle) {
for (const chunk of Object.values(bundle)) {
if (chunk.type === 'chunk' && chunk.name === 'preload-helper') {
// Note: This replacement is dependent on Vite's current implementation of the preload helper.
// It's necessary due to how browsers handle module preloading and credential modes.
// See: https://developer.chrome.com/blog/modulepreload/#ok-so-why-doesnt-link-relpreload-work-for-modules
chunk.code = chunk.code.replace(
/crossOrigin = (['"])(|anonymous|use-credentials)\1/g,
`crossOrigin = "${crossOriginValue}"`
);
}
}
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment