Open emosheeep opened 6 months ago
Unfortunately, the plugin is not supported
emmm,we can use regexp to replace it if the provided library is an external
Like this, and it works for me, maybe inspire you.
import path from 'path';
import { PluginOption } from 'vite';
interface LibItem {
libName: string;
esmDirectory: string;
cjsDirectory: string;
style: (name: string) => string;
camel2DashComponentName?: boolean;
}
/**
* 拓展按需引用插件,根据不同的 format 输出不同的引用路径
*/
export function createDemandImportPlugin(options: LibItem[]): PluginOption {
const cjsReplacer: [RegExp, string][] = options.map((item) => {
return [
new RegExp(`(?<=require\\((['"])${item.libName}\/)(${item.esmDirectory})(?=\/.*?\\1\\))`, 'g'),
item.cjsDirectory,
];
});
return [
// default plugin
{},
// our hack
{
name: 'import:esm-to-cjs',
enforce: 'post',
renderChunk(code, _, { format }) {
return format === 'cjs'
? cjsReplacer.reduce((result, [reg, replacer]) => result.replaceAll(reg, replacer), code)
: null;
},
},
];
}
Describe the feature
If I use it in a library and want to output two formats (esm and cjs), I can transform an import into only one format.
Can this plugin support this case?