vite-import-plugin
Version:
Vite transform import plugin
69 lines (68 loc) • 3.57 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const os_1 = require("os");
const path_1 = require("path");
/*
* viteImportPlugin
* 用于将vite中ui组件的引入方式转换成按需引入
*/
const viteImportPlugin = (options) => {
const { libraryName, libraryDirectory, destructionMode = true, stylePath, debug = false } = options;
//匹配除了被// | /* | * 注释掉的import 语句
const regStr = `(?<![\/\*\ ]+)\ *import \{([^\}]+)\} from [\'\"]${libraryName}[\'\"];?`;
//匹配除了被注释掉的组件
const matchComponet = new RegExp(/^\s*(([^\/\s]+\S+)\s+as\s+(\S+)|\S+)\s*$/);
const importCodeReg = new RegExp(regStr, "g");
const componentsReg = new RegExp(regStr);
return {
name: "vite-import-plugin",
enforce: "pre",
transform(code, id) {
debug && console.time(`translate ${id} time`);
const importCodes = code.match(importCodeReg);
if (importCodes) {
importCodes.forEach(importCode => {
const componentsResult = importCode.match(componentsReg);
if (componentsResult && componentsResult[1]) {
const sourceComponentNames = [];
const aliasComponentNames = componentsResult[1].split(',').map(v => {
const componentName = v.match(matchComponet);
if (componentName && componentName[3]) {
sourceComponentNames.push(componentName[2]);
}
else if (componentName) {
sourceComponentNames.push(componentName[1]);
}
return componentName && (componentName[3] || componentName[2] || componentName[1]);
}).filter(v => v);
let newResult;
if (destructionMode) {
newResult = importCode + os_1.EOL + sourceComponentNames.map((component) => {
return `import "${stylePath(component)}"`;
}).join(os_1.EOL);
}
else {
newResult = aliasComponentNames.map((component, index) => {
const sourceComponent = sourceComponentNames[index];
let componentPath = typeof libraryDirectory === "string" ?
`${libraryName}/${libraryDirectory}/${sourceComponent.toLocaleLowerCase()}` :
libraryDirectory(sourceComponent);
componentPath = path_1.normalize(componentPath);
let style = stylePath(component);
style = path_1.normalize(style);
return `import ${component} from "${componentPath}";${os_1.EOL}import "${style}";`;
}).join(os_1.EOL);
}
if (debug) {
console.debug(`translate ${id} importCode from:\n${importCode}\nto\n${newResult}`);
}
code = code.replace(importCode, newResult);
}
});
}
debug && console.timeEnd(`translate ${id} time`);
return code;
}
};
};
exports.default = viteImportPlugin;