Skip to content

Commit

Permalink
feat: export vite-plugin-svg-icons/client
Browse files Browse the repository at this point in the history
  • Loading branch information
anncwb committed Mar 7, 2021
1 parent a00714c commit fd765cd
Show file tree
Hide file tree
Showing 8 changed files with 61 additions and 12 deletions.
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
dist
node_modules
example
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,13 @@ Here the svg sprite map has been generated

React is used in the same way. Just modify the component to Jsx component

### Get all SymbolId

```ts
import ids from 'vite-plugin-svg-icons/client';
// => ['icon-icon1','icon-icon2','icon-icon3']
```

### Options

| Parameter | Type | Default | Description |
Expand Down
7 changes: 7 additions & 0 deletions README.zh_CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,13 @@ import 'vite-plugin-svg-icons/register';

React 使用方式一样。只需修改组件为 Jsx 组件即可

### 获取所有 SymbolId

```ts
import ids from 'vite-plugin-svg-icons/client';
// => ['icon-icon1','icon-icon2','icon-icon3']
```

### 配置说明

| 参数 | 类型 | 默认值 | 说明 |
Expand Down
4 changes: 4 additions & 0 deletions cliend.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
declare module 'vite-plugin-svg-icons/client' {
const result: string[];
export default result;
}
4 changes: 4 additions & 0 deletions example/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ import App from './App.vue';

import 'vite-plugin-svg-icons/register';

import allKeys from 'vite-plugin-svg-icons/client';

console.log(allKeys);

const app = createApp(App);

app.mount('#app');
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
"author": "Vben",
"files": [
"dist",
"index.d.ts"
"register.d.ts",
"client.d.ts"
],
"scripts": {
"dev": "npm run build -- --watch",
Expand Down
1 change: 1 addition & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export const SVG_ICONS_NAME = 'vite-plugin-svg-icons/register';
export const SVG_ICONS_CLIENT = 'vite-plugin-svg-icons/client';

export const SVG_DOM_ID = '__svg__icons__dom__' + new Date().getTime() + '__';
46 changes: 35 additions & 11 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { optimize } from 'svgo';
import fs from 'fs-extra';
import path from 'path';
import { debug as Debug } from 'debug';
import { SVG_DOM_ID, SVG_ICONS_NAME } from './constants';
import { SVG_DOM_ID, SVG_ICONS_CLIENT, SVG_ICONS_NAME } from './constants';
import { normalizePath } from 'vite';
// @ts-ignore
import SVGCompiler from 'svg-baker';
Expand Down Expand Up @@ -37,6 +37,7 @@ interface FileStats {
relativeName: string;
mtimeMs?: number;
code: string;
symbolId?: string;
}

export default (opt: ViteSvgIconsPlugin): Plugin => {
Expand Down Expand Up @@ -68,25 +69,41 @@ export default (opt: ViteSvgIconsPlugin): Plugin => {
debug('resolvedConfig:', resolvedConfig);
},
resolveId(importee) {
if (importee === SVG_ICONS_NAME) {
if (importee === SVG_ICONS_NAME || importee === SVG_ICONS_CLIENT) {
return importee;
}
return null;
},

async load(id) {
if (id === SVG_ICONS_NAME && isBuild) {
return await createModuleCode(cache, svgoOptions as SvgoOptions, options);
const isRegister = id === SVG_ICONS_NAME;
const isClient = id === SVG_ICONS_CLIENT;
if (isBuild && (isRegister || isClient)) {
const { code, idSet } = await createModuleCode(cache, svgoOptions as SvgoOptions, options);
if (isRegister) {
return code;
}
if (isClient) {
return idSet;
}
}
return null;
},
configureServer: ({ middlewares }) => {
middlewares.use(async (req, res, next) => {
const url = req.url!;
if (normalizePath(url) === `/@id/${SVG_ICONS_NAME}`) {
const url = normalizePath(req.url!);
const registerId = `/@id/${SVG_ICONS_NAME}`;
const clientId = `/@id/${SVG_ICONS_CLIENT}`;
if ([clientId, registerId].includes(url)) {
res.setHeader('Content-Type', 'application/javascript');
res.setHeader('Cache-Control', 'no-cache');
const content = await createModuleCode(cache, svgoOptions as SvgoOptions, options);
const { code, idSet } = await createModuleCode(
cache,
svgoOptions as SvgoOptions,
options
);
const content = url === registerId ? code : idSet;

res.setHeader('Etag', getEtag(content, { weak: true }));
res.statusCode = 200;
res.end(content);
Expand All @@ -103,7 +120,7 @@ export async function createModuleCode(
svgoOptions: SvgoOptions,
options: ViteSvgIconsPlugin
) {
const insertHtml = await compilerIcons(cache, svgoOptions, options);
const { insertHtml, idSet } = await compilerIcons(cache, svgoOptions, options);
const code = `
document.addEventListener('DOMContentLoaded', () => {
let body = document.body;
Expand All @@ -117,7 +134,10 @@ export async function createModuleCode(
body.insertBefore(svgDom, body.firstChild);
});
`;
return `${code}\nexport default {}`;
return {
code: `${code}\nexport default {}`,
idSet: `export default ${JSON.stringify(Array.from(idSet))}`,
};
}

/**
Expand All @@ -133,6 +153,7 @@ export async function compilerIcons(
const { iconDirs } = options;

let insertHtml = '';
const idSet = new Set<string>();

for (const dir of iconDirs) {
const svgFilsStats = fg.sync('**/*.svg', { cwd: dir, stats: true, absolute: true });
Expand All @@ -148,13 +169,16 @@ export async function compilerIcons(
relativeName = normalizePath(path).replace(normalizePath(dir + '/'), '');
symbolId = createSymbolId(relativeName, options);
svgSymbol = await compilerIcon(path, symbolId, svgOptions);
idSet.add(symbolId);
};

if (cacheStat) {
if (cacheStat.mtimeMs !== mtimeMs) {
await getSymbol();
} else {
svgSymbol = cacheStat.code;
symbolId = cacheStat.symbolId;
symbolId && idSet.add(symbolId);
}
} else {
await getSymbol();
Expand All @@ -165,12 +189,12 @@ export async function compilerIcons(
mtimeMs,
relativeName,
code: svgSymbol,
symbolId,
});
insertHtml += `${svgSymbol || ''}`;
}
}

return insertHtml;
return { insertHtml, idSet };
}

export async function compilerIcon(
Expand Down

0 comments on commit fd765cd

Please sign in to comment.