aleclarson / vite-tsconfig-paths

Support for TypeScript's path mapping in Vite
MIT License
1.24k stars 43 forks source link

Cannot get the name of this plugin #78

Closed rmariuzzo closed 1 year ago

rmariuzzo commented 1 year ago

I would like to filter this plugin when merging multiple vite config. I can do the filtering using its name as follow:

mergeConfig(config, {
  plugins: [
    ...config.plugins.filter(plugin => plugin.name !== 'vite-tsconfig-paths'), // πŸ‘ˆ Filtering plugin.
    tsConfigPaths(...), // πŸ‘ˆ Using different config.
  ]
})

However, instead of using a hard coded name, I would prefer to have access to its defined name: https://github.com/aleclarson/vite-tsconfig-paths/blob/44a9f7765c4072deaee0c5b1392445c64fb21a94/src/index.ts#L26

One idea would be to export the name as a props of the function and we would be able to access it as:

tsConfigPaths.pluginName // πŸ‘ˆ using `pluginName` instead of `name` which is a prop inherited from `Function.name`.

Or you could export the plugin name as:

export const pluginName = 'vite-tsconfig-paths'
aleclarson commented 1 year ago

Does this work for you?

function replaceTsConfigPaths(plugins, options) {
  const plugin = tsConfigPaths(options)
  return [
    ...plugins.filter(p => p.name !== plugin.name),
    plugin,
  ]
}
rmariuzzo commented 1 year ago

Thank you for the idea, I ended up with something similar but more verbose because Vite's PluginOption is a union of many types:

// node_modules/vite/dist/node/index.d.ts
export declare type PluginOption = Plugin_2 | false | null | undefined | PluginOption[] | Promise<Plugin_2 | false | null | undefined | PluginOption[]>;

Solution:

const plugin = tsConfigPaths(options)
return mergeConfig(config, {
  plugins: [
    ...(config.plugins
      // πŸ‘‡Needed because `PluginOption` can be a value or a promise.
      ? (await Promise.all(config.plugins)).filter((p) => {
          // πŸ‘‡ Needed because `PluginOption` can be `false | null | undefined | PluginOption[]`
          return p && !Array.isArray(p) && p.name !== plugin.name;
        })
      : []),
    plugin,
  ],
});