index.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. var __create = Object.create;
  2. var __defProp = Object.defineProperty;
  3. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  4. var __getOwnPropNames = Object.getOwnPropertyNames;
  5. var __getProtoOf = Object.getPrototypeOf;
  6. var __hasOwnProp = Object.prototype.hasOwnProperty;
  7. var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
  8. var __export = (target, all) => {
  9. for (var name in all)
  10. __defProp(target, name, { get: all[name], enumerable: true });
  11. };
  12. var __reExport = (target, module2, copyDefault, desc) => {
  13. if (module2 && typeof module2 === "object" || typeof module2 === "function") {
  14. for (let key of __getOwnPropNames(module2))
  15. if (!__hasOwnProp.call(target, key) && (copyDefault || key !== "default"))
  16. __defProp(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
  17. }
  18. return target;
  19. };
  20. var __toESM = (module2, isNodeMode) => {
  21. return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", !isNodeMode && module2 && module2.__esModule ? { get: () => module2.default, enumerable: true } : { value: module2, enumerable: true })), module2);
  22. };
  23. var __toCommonJS = /* @__PURE__ */ ((cache) => {
  24. return (module2, temp) => {
  25. return cache && cache.get(module2) || (temp = __reExport(__markAsModule({}), module2, 1), cache && cache.set(module2, temp), temp);
  26. };
  27. })(typeof WeakMap !== "undefined" ? /* @__PURE__ */ new WeakMap() : 0);
  28. // src/index.ts
  29. var src_exports = {};
  30. __export(src_exports, {
  31. AndDesignVueResolve: () => AndDesignVueResolve,
  32. AntdResolve: () => AntdResolve,
  33. ElementPlusResolve: () => ElementPlusResolve,
  34. NutuiResolve: () => NutuiResolve,
  35. VantResolve: () => VantResolve,
  36. VxeTableResolve: () => VxeTableResolve,
  37. default: () => src_default,
  38. getChangeCaseFileName: () => getChangeCaseFileName,
  39. transformImportVar: () => transformImportVar
  40. });
  41. // node_modules/tsup/assets/cjs_shims.js
  42. var getImportMetaUrl = () => typeof document === "undefined" ? new URL("file:" + __filename).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
  43. var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
  44. // src/index.ts
  45. var import_pluginutils = require("@rollup/pluginutils");
  46. var changeCase = __toESM(require("change-case"));
  47. var import_es_module_lexer = require("es-module-lexer");
  48. var import_magic_string = __toESM(require("magic-string"));
  49. var import_path2 = __toESM(require("path"));
  50. var import_fs2 = __toESM(require("fs"));
  51. var import_debug = __toESM(require("debug"));
  52. // src/utils.ts
  53. var import_path = __toESM(require("path"));
  54. var import_vite = require("vite");
  55. var import_fs = __toESM(require("fs"));
  56. var import_module = require("module");
  57. function resolveNodeModules(libName, ...dir) {
  58. const esRequire = (0, import_module.createRequire)(importMetaUrl);
  59. let modulePath = "";
  60. try {
  61. modulePath = (0, import_vite.normalizePath)(esRequire.resolve(libName));
  62. } catch (error) {
  63. modulePath = (0, import_vite.normalizePath)(require.resolve(libName));
  64. }
  65. const lastIndex = modulePath.lastIndexOf(libName);
  66. return (0, import_vite.normalizePath)(import_path.default.resolve(modulePath.substring(0, lastIndex), ...dir));
  67. }
  68. function resolvePnp(module2) {
  69. try {
  70. return (0, import_vite.normalizePath)(require.resolve(module2));
  71. } catch (error) {
  72. return "";
  73. }
  74. }
  75. var isPnp = !!process.versions.pnp;
  76. function isRegExp(value) {
  77. return Object.prototype.toString.call(value) === "[object RegExp]";
  78. }
  79. function fileExists(f) {
  80. try {
  81. import_fs.default.accessSync(f, import_fs.default.constants.W_OK);
  82. return true;
  83. } catch (error) {
  84. return false;
  85. }
  86. }
  87. // src/resolve/antd.ts
  88. function AntdResolve() {
  89. return {
  90. libraryName: "antd",
  91. esModule: true,
  92. resolveStyle: (name) => {
  93. return `antd/es/${name}/style/index`;
  94. }
  95. };
  96. }
  97. // src/resolve/antdv.ts
  98. function AndDesignVueResolve() {
  99. return {
  100. ensureStyleFile: true,
  101. libraryName: "ant-design-vue",
  102. esModule: true,
  103. resolveStyle: (name) => {
  104. return `ant-design-vue/es/${name}/style/index`;
  105. }
  106. };
  107. }
  108. // src/resolve/elementPlus.ts
  109. function ElementPlusResolve() {
  110. return {
  111. libraryName: "element-plus",
  112. ensureStyleFile: true,
  113. esModule: true,
  114. resolveStyle: (name) => {
  115. return `element-plus/theme-chalk/${name}.css`;
  116. },
  117. resolveComponent: (name) => {
  118. return `element-plus/es/components/${name.replace(/^el-/, "")}/index.mjs`;
  119. },
  120. base: "element-plus/theme-chalk/base.css"
  121. };
  122. }
  123. // src/resolve/vant.ts
  124. function VantResolve() {
  125. return {
  126. libraryName: "vant",
  127. esModule: true,
  128. resolveStyle: (name) => {
  129. return `vant/es/${name}/style`;
  130. }
  131. };
  132. }
  133. // src/resolve/nutui.ts
  134. function NutuiResolve() {
  135. return {
  136. libraryName: "@nutui/nutui",
  137. libraryNameChangeCase: "pascalCase",
  138. resolveStyle: (name) => {
  139. return `@nutui/nutui/dist/packages/${name}/index.scss`;
  140. }
  141. };
  142. }
  143. // src/resolve/vxeTable.ts
  144. function VxeTableResolve() {
  145. return {
  146. ensureStyleFile: true,
  147. libraryName: "vxe-table",
  148. esModule: true,
  149. resolveStyle: (name) => {
  150. return `vxe-table/es/${name}/style.css`;
  151. }
  152. };
  153. }
  154. // src/index.ts
  155. var debug = (0, import_debug.default)("vite-plugin-style-import");
  156. var ensureFileExts = [".css", ".js", ".scss", ".less", ".styl"];
  157. var asRE = /\s+as\s+\w+,?/g;
  158. var isFn = (value) => value != null && Object.prototype.toString.call(value) === "[object Function]";
  159. var src_default = (options) => {
  160. const {
  161. include = ["**/*.vue", "**/*.ts", "**/*.js", "**/*.tsx", "**/*.jsx"],
  162. exclude = "node_modules/**",
  163. resolves = []
  164. } = options;
  165. let { libs = [] } = options;
  166. libs = [...libs, ...resolves];
  167. const filter = (0, import_pluginutils.createFilter)(include, exclude);
  168. let needSourcemap = false;
  169. let isBuild = false;
  170. let external;
  171. debug("plugin options:", options);
  172. return {
  173. name: "vite:style-import",
  174. enforce: "post",
  175. configResolved(resolvedConfig) {
  176. var _a, _b, _c;
  177. needSourcemap = !!resolvedConfig.build.sourcemap;
  178. isBuild = resolvedConfig.isProduction || resolvedConfig.command === "build";
  179. external = (_c = (_b = (_a = resolvedConfig == null ? void 0 : resolvedConfig.build) == null ? void 0 : _a.rollupOptions) == null ? void 0 : _b.external) != null ? _c : void 0;
  180. debug("plugin config:", resolvedConfig);
  181. },
  182. async transform(code, id) {
  183. if (!code || !filter(id) || !needTransform(code, libs)) {
  184. return null;
  185. }
  186. await import_es_module_lexer.init;
  187. let imports = [];
  188. try {
  189. imports = (0, import_es_module_lexer.parse)(code)[0];
  190. debug("imports:", imports);
  191. } catch (e) {
  192. debug("imports-error:", e);
  193. }
  194. if (!imports.length) {
  195. return null;
  196. }
  197. let s;
  198. const str = () => s || (s = new import_magic_string.default(code));
  199. for (let index = 0; index < imports.length; index++) {
  200. const { n, se, ss } = imports[index];
  201. if (!n)
  202. continue;
  203. const lib = getLib(n, libs, external);
  204. if (!lib)
  205. continue;
  206. const isResolveComponent = isBuild && !!lib.resolveComponent;
  207. const importStr = code.slice(ss, se);
  208. let importVariables = transformImportVar(importStr);
  209. importVariables = filterImportVariables(importVariables, lib.importTest);
  210. const importCssStrList = await transformComponentCss(lib, importVariables);
  211. let compStrList = [];
  212. let compNameList = [];
  213. if (isResolveComponent) {
  214. const { componentStrList, componentNameList } = transformComponent(lib, importVariables);
  215. compStrList = componentStrList;
  216. compNameList = componentNameList;
  217. }
  218. debug("prepend import css str:", importCssStrList.join(""));
  219. debug("prepend import component str:", compStrList.join(""));
  220. const { base = "" } = lib;
  221. let baseImporter = base ? `
  222. import '${base}'` : "";
  223. if (str().toString().includes(base)) {
  224. baseImporter = "";
  225. }
  226. const endIndex = se + 1;
  227. if (isResolveComponent && compNameList.some((item) => importVariables.includes(item))) {
  228. if (lib.libraryName === "element-plus") {
  229. str().remove(ss, endIndex);
  230. } else {
  231. const importStr2 = str().slice(ss, endIndex);
  232. const [resultStr, uncssList] = await removeAlreadyName(importStr2, lib);
  233. if (resultStr) {
  234. str().overwrite(ss, endIndex, resultStr);
  235. } else {
  236. str().remove(ss, endIndex);
  237. }
  238. if (uncssList.length) {
  239. compStrList = compStrList.filter((item) => !uncssList.some((imp) => item.startsWith(`import ${imp}`)));
  240. }
  241. }
  242. }
  243. str().prependRight(endIndex, `${baseImporter}
  244. ${compStrList.join("")}${importCssStrList.join("")}`);
  245. }
  246. return {
  247. map: needSourcemap ? str().generateMap({ hires: true }) : null,
  248. code: str().toString()
  249. };
  250. }
  251. };
  252. };
  253. function filterImportVariables(importVars, reg) {
  254. if (!reg) {
  255. return importVars;
  256. }
  257. return importVars.filter((item) => reg.test(item));
  258. }
  259. async function removeAlreadyName(importStr, lib) {
  260. let result = importStr;
  261. const { libraryNameChangeCase = "paramCase", resolveStyle, libraryName } = lib;
  262. const exportStr = importStr.replace(asRE, ",").replace("import", "export").replace(asRE, ",");
  263. await import_es_module_lexer.init;
  264. const importComponents = (0, import_es_module_lexer.parse)(exportStr)[1];
  265. const hasCssList = [];
  266. const unCssList = [];
  267. importComponents.filter((comp) => {
  268. const name = getChangeCaseFileName(comp, libraryNameChangeCase);
  269. const importStr2 = resolveStyle == null ? void 0 : resolveStyle(name);
  270. if (importStr2) {
  271. const cssFile = resolveNodeModules(libraryName, importStr2);
  272. if (import_fs2.default.existsSync(cssFile)) {
  273. hasCssList.push(comp);
  274. } else {
  275. unCssList.push(comp);
  276. }
  277. } else {
  278. unCssList.push(comp);
  279. }
  280. });
  281. hasCssList.forEach((item) => {
  282. result = result.replace(new RegExp(`\\s?${item}\\s?,?`), "");
  283. });
  284. if ((0, import_es_module_lexer.parse)(result.replace("import", "export"))[1].length === 0) {
  285. result = "";
  286. }
  287. return [result, unCssList];
  288. }
  289. async function transformComponentCss(lib, importVariables) {
  290. const {
  291. libraryName,
  292. resolveStyle,
  293. esModule,
  294. libraryNameChangeCase = "paramCase",
  295. ensureStyleFile = false
  296. } = lib;
  297. if (!isFn(resolveStyle) || !libraryName) {
  298. return [];
  299. }
  300. const set = /* @__PURE__ */ new Set();
  301. for (let index = 0; index < importVariables.length; index++) {
  302. const name = getChangeCaseFileName(importVariables[index], libraryNameChangeCase);
  303. let importStr = resolveStyle(name);
  304. if (!importStr) {
  305. continue;
  306. }
  307. let isAdd = true;
  308. if (isPnp) {
  309. importStr = resolvePnp(importStr);
  310. isAdd = !!importStr;
  311. } else {
  312. if (esModule) {
  313. importStr = resolveNodeModules(libraryName, importStr);
  314. }
  315. if (ensureStyleFile) {
  316. isAdd = ensureFileExists(libraryName, importStr, esModule);
  317. }
  318. }
  319. isAdd && set.add(`import '${importStr}';
  320. `);
  321. }
  322. debug("import css sets:", set.toString());
  323. return Array.from(set);
  324. }
  325. function transformComponent(lib, importVariables) {
  326. const {
  327. libraryName,
  328. resolveComponent,
  329. libraryNameChangeCase = "paramCase",
  330. transformComponentImportName
  331. } = lib;
  332. if (!isFn(resolveComponent) || !libraryName) {
  333. return {
  334. componentStrList: [],
  335. componentNameList: []
  336. };
  337. }
  338. const componentNameSet = /* @__PURE__ */ new Set();
  339. const componentStrSet = /* @__PURE__ */ new Set();
  340. for (let index = 0; index < importVariables.length; index++) {
  341. const libName = importVariables[index];
  342. const name = getChangeCaseFileName(importVariables[index], libraryNameChangeCase);
  343. const importStr = resolveComponent(name);
  344. const importLibName = isFn(transformComponentImportName) && transformComponentImportName(libName) || libName;
  345. componentStrSet.add(`import ${importLibName} from '${importStr}';
  346. `);
  347. componentNameSet.add(libName);
  348. }
  349. debug("import component set:", componentStrSet.toString());
  350. return {
  351. componentStrList: Array.from(componentStrSet),
  352. componentNameList: Array.from(componentNameSet)
  353. };
  354. }
  355. function transformImportVar(importStr) {
  356. if (!importStr) {
  357. return [];
  358. }
  359. const exportStr = importStr.replace("import", "export").replace(asRE, ",");
  360. let importVariables = [];
  361. try {
  362. importVariables = (0, import_es_module_lexer.parse)(exportStr)[1];
  363. debug("importVariables:", importVariables);
  364. } catch (error) {
  365. debug("transformImportVar:", error);
  366. }
  367. return importVariables;
  368. }
  369. function ensureFileExists(libraryName, importStr, esModule = false) {
  370. const extName = import_path2.default.extname(importStr);
  371. if (!extName) {
  372. return tryEnsureFile(libraryName, importStr, esModule);
  373. }
  374. if (esModule) {
  375. return fileExists(importStr);
  376. }
  377. return true;
  378. }
  379. function tryEnsureFile(libraryName, filePath, esModule = false) {
  380. const filePathList = ensureFileExts.map((item) => {
  381. const p = `${filePath}${item}`;
  382. return esModule ? p : resolveNodeModules(libraryName, p);
  383. });
  384. return filePathList.some((item) => fileExists(item));
  385. }
  386. function getLib(libraryName, libs, external) {
  387. let libList = libs;
  388. if (external) {
  389. const isString = typeof external === "string";
  390. const isRE = isRegExp(external);
  391. if (isString) {
  392. libList = libList.filter((item) => item.libraryName !== external);
  393. } else if (isRE) {
  394. libList = libList.filter((item) => !external.test(item.libraryName));
  395. } else if (Array.isArray(external)) {
  396. libList = libList.filter((item) => {
  397. return !external.some((val) => {
  398. if (typeof val === "string") {
  399. return val === item.libraryName;
  400. }
  401. return val.test(item.libraryName);
  402. });
  403. });
  404. }
  405. }
  406. return libList.find((item) => item.libraryName === libraryName);
  407. }
  408. function getChangeCaseFileName(importedName, libraryNameChangeCase) {
  409. try {
  410. return changeCase[libraryNameChangeCase](importedName);
  411. } catch (error) {
  412. return importedName;
  413. }
  414. }
  415. function needTransform(code, libs) {
  416. return !libs.every(({ libraryName }) => {
  417. return !new RegExp(`('${libraryName}')|("${libraryName}")`).test(code);
  418. });
  419. }
  420. module.exports = __toCommonJS(src_exports);
  421. // Annotate the CommonJS export names for ESM import in node:
  422. 0 && (module.exports = {
  423. AndDesignVueResolve,
  424. AntdResolve,
  425. ElementPlusResolve,
  426. NutuiResolve,
  427. VantResolve,
  428. VxeTableResolve,
  429. getChangeCaseFileName,
  430. transformImportVar
  431. });