@viteworks/vite-plugin-external-globals-chain
v0.0.3
Published
A Vite plugin wrapper for vite-plugin-external that supports array-based global variable paths
Downloads
17
Maintainers
Readme
@viteworks/vite-plugin-external-globals-chain
A powerful Vite plugin that allows you to externalize dependencies and map them to global variables with support for array-based nested paths. This plugin transforms import statements to access global variables, enabling you to use CDN-loaded libraries while maintaining clean import syntax in your code.
Features
- 🎯 Array-based configuration: Use arrays to define nested global variable paths
- 🔄 Automatic conversion: Arrays are converted to
window.x.y.zformat automatically - 🛡️ Type safety: Full TypeScript support with comprehensive type definitions
- ⚡ Zero overhead: Minimal wrapper that delegates to vite-plugin-external
- 🧪 Well tested: Comprehensive test suite with 100% coverage
Installation
npm install @viteworks/vite-plugin-external-globals-chain
# or
yarn add @viteworks/vite-plugin-external-globals-chain
# or
pnpm add @viteworks/vite-plugin-external-globals-chainUsage
Basic Example
// vite.config.ts
import { defineConfig } from "vite";
import windowExternal from "@viteworks/vite-plugin-external-globals-chain";
export default defineConfig({
plugins: [
windowExternal({
// Array format - converted to 'window.ralWindows.React'
react: ["ralWindows", "React"],
// Array format - converted to 'window.ralWindows.ReactDOM'
"react-dom": ["ralWindows", "ReactDOM"],
// String format - passed through unchanged
lodash: "window._",
}),
],
});Advanced Configuration
// vite.config.ts
import { defineConfig } from "vite";
import windowExternal from "@viteworks/vite-plugin-external-globals-chain";
export default defineConfig({
plugins: [
windowExternal({
// Deep nesting support
"some-library": ["MyApp", "vendors", "SomeLibrary"],
// Result: 'window.MyApp.vendors.SomeLibrary'
// Mixed configuration
jquery: "window.$",
moment: ["MyApp", "libs", "moment"],
// Single-level arrays
axios: ["httpClient"],
// Result: 'window.httpClient'
}),
],
});HTML Setup
Make sure your HTML includes the global variables before your bundled code:
<!DOCTYPE html>
<html>
<head>
<script>
// Set up global variables that match your configuration
window.ralWindows = {
React: React,
ReactDOM: ReactDOM,
};
window.MyApp = {
vendors: {
SomeLibrary: SomeLibrary,
},
libs: {
moment: moment,
},
};
</script>
<!-- Load your external libraries -->
<script src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>API Reference
windowExternal(config: WindowExternalConfig): Plugin
The main plugin function that accepts a configuration object and returns a Vite plugin.
Parameters
config: WindowExternalConfig- Configuration object mapping package names to global variable paths
Returns
Plugin- A Vite plugin instance
Types
WindowExternalConfig
interface WindowExternalConfig {
[packageName: string]: ExternalValue;
}Configuration interface for the plugin. Maps package names to their global variable paths.
ExternalValue
type ExternalValue = string[] | string;The value type for external dependencies:
string[]: Array of path segments that will be joined with dots and prefixed with 'window.'string: Direct global variable path (passed through unchanged)
Configuration Rules
Array Values
When you provide an array value:
Non-empty arrays: Arrays must contain at least one element
// ✅ Valid 'react': ['MyNamespace', 'React'] // ❌ Invalid - will throw error 'react': []String elements only: All array elements must be strings
// ✅ Valid 'lodash': ['utils', 'lodash'] // ❌ Invalid - will throw TypeError 'lodash': ['utils', 123, 'lodash']Automatic prefixing: Arrays are automatically prefixed with 'window.'
// Input 'react': ['MyApp', 'React'] // Output (passed to vite-plugin-external) 'react': 'window.MyApp.React'
String Values
String values are passed through unchanged to vite-plugin-external:
// Input
'jquery': 'window.$'
// Output (passed to vite-plugin-external)
'jquery': 'window.$'Error Handling
The plugin provides clear error messages for invalid configurations:
Empty Array Error
// This will throw: Error('External value array for "react" cannot be empty')
windowExternal({
react: [],
});Type Error
// This will throw: TypeError('All array elements for "react" must be strings')
windowExternal({
react: ["MyApp", 123, "React"],
});Development
Setup
# Clone the repository
git clone https://github.com/viteworks/vite-plugins.git
cd vite-plugins/packages/vite-plugin-external-globals-chain
# Install dependencies
npm installScripts
# Build the project
npm run build
# Build with clean dist folder
npm run build:clean
# Run tests
npm run test
# Run tests in watch mode
npm run test:watch
# Run tests with coverage
npm run test:coverage
# Type checking
npm run lint
# Development mode (watch build)
npm run devProject Structure
├── src/
│ ├── index.ts # Main plugin export
│ ├── transform.ts # Configuration transformation logic
│ └── types.ts # TypeScript type definitions
├── tests/
│ ├── transform.test.ts # Unit tests for transformation logic
│ ├── integration.test.ts # Integration tests with vite-plugin-external
│ └── e2e.test.ts # End-to-end tests
├── dist/ # Built files (generated)
├── package.json # Package configuration
├── tsconfig.json # TypeScript configuration
├── tsconfig.build.json # Build-specific TypeScript config
└── vitest.config.ts # Test configurationContributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Make your changes
- Add tests for your changes
- Ensure all tests pass (
npm test) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Related Projects
- vite-plugin-external - The underlying plugin this wrapper extends
- Vite - Next generation frontend tooling
Changelog
1.0.0
- Initial release
- Array-based configuration support
- Full TypeScript support
- Comprehensive test suite
