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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@open-xchange/vite-plugin-replace-pkg

v0.0.3

Published

Vite plugin replacing a specific external package with an arbitrary source code module

Downloads

785

Readme

@open-xchange/vite-plugin-replace-pkg

A Vite plugin that replaces a specific external package with an arbitrary source code module.

Usage

This plugin replaces a specific external package with a custom source file that can be downloaded from an arbitrary URL, or that can be extracted from a GitLab project repository. If the replacement source file cannot be resolved, the original external package will be used.

A common use case is replacing a public package with an internally hosted commercial version of the package. When building the product internally, the internal version of the package will be bundled, otherwise the public version.

// vite.config.ts

import { defineConfig } from "vite" // or "vitest/config"
import replacePlugin from "@open-xchange/vite-plugin-replace-pkg"

export default defineConfig(() => {
  plugins: [
    replacePlugin({
      package: "external-package",
      replace: "https://example.org/path/to/index.js",
    }),
  ],
})
// src/index.ts

import * as ext from "external-package" // imports replacement if available

It is possible to replace different packages by instantiating this plugin multiple times:

// vite.config.ts

import { defineConfig } from "vite" // or "vitest/config"
import replacePlugin from "@open-xchange/vite-plugin-replace-pkg"

export default defineConfig(() => {
  plugins: [
    replacePlugin({
      package: "external-package",
      replace: "https://example.org/path/to/index.js",
    }),
    replacePlugin({
      package: "@namespace/another-package",
      replace: { /* GitLab project file */ },
    }),
  ],
})

Options

Option package

  • Type: string
  • required

The name of the external package to be replaced, as appearing in import statements in source code.

Option replace

  • Type: various (see below)
  • required

The location of the source file to resolve the module imports with. There are different ways to declare the source file:

  1. A simple URL as string (see above for an example).

  2. A RequestInit configuration object for the fetch function (headers, body, etc.), with the following additional options:

    | Name | Type | Default | Description | | - | - | - | - | | url | string | required | The URL of the source file to be downloaded. | | query | Dict<string\|number\|boolean> | {} | Query parameters to be added to the URL. |

    Example:

    // vite.config.ts
    
    import { defineConfig } from "vite" // or "vitest/config"
    import replacePlugin from "@open-xchange/vite-plugin-replace-pkg"
    
    export default defineConfig(() => {
      plugins: [
        replacePlugin({
          package: "external-package",
          replace: {
            method: "POST",
            headers: { "X-Some-Header", "abc" },
            url: "https://example.org/api/to/endpoint",
            query: { ts: Date.now() },
          },
        }),
      ],
    })
  3. A specification for a file in a GitLab project repository, with the following options:

    | Name | Type | Default | Description | | - | - | - | - | | server | string | required | The URL of the GitLab server to be used for downloading the source file. | | project | string\|number | required | Name or numeric identifier of the GitLab project. The project name may contain slashes (e.g. "my-group/my-project") which will be encoded internally. | | path | string | required | Path to the source file to be downloaded. Slashes in the path will be encoded internally. | | ref | string | HEAD | The name of a branch or tag, or a commit ID. Slashes in branch names will be encoded internally. | | token | string | environment variable GITLAB_TOKEN | A valid GitLab API access token. If omitted, uses the contents of the environment variable GITLAB_TOKEN. If the resulting token is empty, downloading the source file will be skipped silently. |

    Example:

    // vite.config.ts
    
    import { defineConfig } from "vite" // or "vitest/config"
    import replacePlugin from "@open-xchange/vite-plugin-replace-pkg"
    
    export default defineConfig(() => {
      plugins: [
        replacePlugin({
          package: "external-package",
          replace: {
            server: "https://gitlab.example.org",
            project: "internals/commercial-package",
            path: "path/to/index.js",
            ref: "feature/branch-2",
          },
        }),
      ],
    })
  4. A custom callback function. Will be invoked with the original package name (the value of the option package), and returns the source code to be used instead.

    Example:

    // vite.config.ts
    
    import { defineConfig } from "vite" // or "vitest/config"
    import replacePlugin from "@open-xchange/vite-plugin-replace-pkg"
    
    export default defineConfig(() => {
      plugins: [
        replacePlugin({
          package: "external-package",
          async replace() { /* ... */ },
        }),
      ],
    })

Option transform

  • Type: (source: string) => string | string[] | Promise<string | string[]>
  • optional

Transformation filter for the source code. The function will be invoked with the downloaded source code, and returns the transformed source code to be used. An array of strings will be concatenated with newline characters.

Example:

// vite.config.ts

import { defineConfig } from "vite" // or "vitest/config"
import replacePlugin from "@open-xchange/vite-plugin-replace-pkg"

export default defineConfig(() => {
  plugins: [
    replacePlugin({
      package: "external-package"
      replace: "https://example.org/path/to/index.js",
      transform: source => source.replaceAll(/* ... */)
    }),
  ],
})

Option prepend

  • Type: string | string[]
  • optional

Inserts arbitrary source code to the beginning of the replacement module. An array of strings will be concatenated with newline characters.

This option will be applied after source code transformation (option transform).

Example:

// vite.config.ts

import { defineConfig } from "vite" // or "vitest/config"
import replacePlugin from "@open-xchange/vite-plugin-replace-pkg"

export default defineConfig(() => {
  plugins: [
    replacePlugin({
      package: "external-package"
      replace: "https://example.org/path/to/index.js",
      prepend: [/* ... */],
    }),
  ],
})

Option append

  • Type: string | string[]
  • optional

Inserts arbitrary source code to the end of the replacement module. An array of strings will be concatenated with newline characters.

This option will be applied after source code transformation (option transform).

Example:

// vite.config.ts

import { defineConfig } from "vite" // or "vitest/config"
import replacePlugin from "@open-xchange/vite-plugin-replace-pkg"

export default defineConfig(() => {
  plugins: [
    replacePlugin({
      package: "external-package"
      replace: "https://example.org/path/to/index.js",
      append: [/* ... */],
    }),
  ],
})

Option exportGlobal

  • Type: string
  • optional

Specifies the name of a global variable that will be defined by the replacement module. This plugin will append source code to the replacement module that will delete the variable from global scope, and will export it as the default export instead.

This option will be applied after source code transformation (option transform).

Example:

// vite.config.ts

import { defineConfig } from "vite" // or "vitest/config"
import replacePlugin from "@open-xchange/vite-plugin-replace-pkg"

export default defineConfig(() => {
  plugins: [
    replacePlugin({
      package: "external-package"
      replace: "https://example.org/path/to/index.js",
      exportGlobal: "TheModule",
    }),
  ],
})

is equivalent to

// vite.config.ts

// ...
    replacePlugin({
      package: "external-package"
      replace: "https://example.org/path/to/index.js",
      append: [
        "const __contents = globalThis.TheModule",
        "delete globalThis.TheModule",
        "export default __contents",
      ],
    }),

Logging

By default, warning messages and error messages will be logged to the shell. The environment variable PLUGIN_REPLACE_PKG_LOGLEVEL can be used to change the log level of this plugin. Possible values are info, warn, error, and silent.