npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@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

Readme

@viteworks/vite-plugin-external-globals-chain

npm version License: MIT

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.z format 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-chain

Usage

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:

  1. Non-empty arrays: Arrays must contain at least one element

    // ✅ Valid
    'react': ['MyNamespace', 'React']
    
    // ❌ Invalid - will throw error
    'react': []
  2. String elements only: All array elements must be strings

    // ✅ Valid
    'lodash': ['utils', 'lodash']
    
    // ❌ Invalid - will throw TypeError
    'lodash': ['utils', 123, 'lodash']
  3. 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 install

Scripts

# 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 dev

Project 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 configuration

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Add tests for your changes
  5. Ensure all tests pass (npm test)
  6. Commit your changes (git commit -m 'Add some amazing feature')
  7. Push to the branch (git push origin feature/amazing-feature)
  8. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Related Projects

Changelog

1.0.0

  • Initial release
  • Array-based configuration support
  • Full TypeScript support
  • Comprehensive test suite