npm package: @open-xchange/vite-plugin-replace-pkg
Description: Vite plugin replacing a specific external package with an arbitrary source code module
Latest version: 1.3.0

# @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.

```ts
// 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',
    }),
  ],
})
```

```ts
// 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:

```ts
// 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`](https://developer.mozilla.org/en-US/docs/Web/API/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` | `Record<string, string\|number\|boolean>` | `{}` | Query parameters to be added to the URL. |

   Example:

   ```ts
   // 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:

   ```ts
   // 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:

   ```ts
   // 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:

```ts
// 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:

```ts
// 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:

```ts
// 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:

```ts
// 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

```ts
// 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`.