Skip to content

Share node_modules in monorepos. Best friend for pnpm's module isolation and module singletons sharing.

Notifications You must be signed in to change notification settings

zheeeng/vite-plugin-shared-modules

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Jun 23, 2024
41180a3 · Jun 23, 2024

History

41 Commits
Dec 21, 2023
Oct 6, 2021
May 31, 2022
Oct 6, 2021
Oct 6, 2021
Oct 6, 2021
Oct 6, 2021
Oct 6, 2021
Nov 17, 2021
Nov 17, 2021
Oct 6, 2021
Aug 1, 2023
Jun 21, 2024
Oct 6, 2021
Oct 7, 2021

Repository files navigation

vite-plugin-shared-modules

Known Vulnerabilities Maintainability publish workflow license GitHub issues NPM bundle size(minified + gzip)

NPM

Share node_modules in monorepos. Best friend for pnpm's module isolation and module singletons sharing.

Use it as simple as:

// vite.config.ts
import { defineConfig } from 'vite';
import sharedModulesPlugin from 'vite-plugin-shared-modules'
import tsconfigPaths from 'rollup-plugin-tsconfig-paths';

export default defineConfig({
  plugins: [
    sharedModulesPlugin({
      packageName: '@monorepo/shared',
    }),
    // necessary for resolving modules in `node_modules`
    tsconfigPaths({
      // specify the project's tsconfig.json, which configured paths mapping.
      tsConfigPath: join(__dirname, '../../tsconfig.json')
    }),
  ]
});

then you can import singletons by this way:

import foo from '@monorepo/shared/foo'
import bar from '@monorepo/shared/bar'

is equivalent to

import foo from '@monorepo/shared/node_modules/foo'
import bar from '@monorepo/shared/node_modules/bar'

moreover for getting type-safe, add tsconfig paths mapping:

// tsconfig.json
{
    "compilerOptions": {
        "baseUrl": ".",
            "paths": {
                "@monorepo/shared/*": ["./packages/shared/node_modules/*", "./packages/shared/node_modules/@types/*"]
            }
    }
}

the example above we assume the package @monorepo/shared is located under ./packages/shared.


Full Option

The plugin options signatures:

export type SharedModulesPluginOption = {
  packageName: string,
  subpath?: string,
  nodeModules?: string,
  sourceMap?: boolean,
}

The default options:

export const defaultSharedModules = {
  subpath: '',
  nodeModules: 'node_modules',
  sourceMap: true,
}