Skip to content

Commit

Permalink
Introduce new option allowWriteFilesInBuild. (#35)
Browse files Browse the repository at this point in the history
  • Loading branch information
atlowChemi authored Jul 3, 2024
1 parent 99142cd commit f34da69
Show file tree
Hide file tree
Showing 6 changed files with 64 additions and 12 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,4 @@ node_modules/
.idea

dist
src/fixtures/webfont-test/artifacts/*
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,12 @@ The plugin has an API consisting of one required parameter and multiple optional
- **description**: Inline font assets in CSS using base64 encoding.
- **default** `false`

### allowWriteFilesInBuild

- **type**: `boolean`
- **description**: Allow outputting assets (HTML, CSS, and Fonts) during build. [see](https://github.com/atlowChemi/vite-svg-2-webfont/issues/32#issuecomment-2203187501)
- **default** `false`

## Public API

The plugin exposes a public API that can be used inside another plugins using [Rollup inter-plugin communication mechanism](https://rollupjs.org/plugin-development/#inter-plugin-communication).
Expand Down
21 changes: 21 additions & 0 deletions src/fixtures/vite.allowWriteFilesInBuild.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { resolve } from 'path';
import { defineConfig } from 'vite';
import { viteSvgToWebfont } from '../../';

const webfontFolder = resolve(__dirname, './webfont-test/svg');
const outputFolder = resolve(__dirname, './webfont-test/artifacts');

export default defineConfig({
build: {
assetsInlineLimit: 0,
},
plugins: [
viteSvgToWebfont({
dest: outputFolder,
generateFiles: true,
context: webfontFolder,
allowWriteFilesInBuild: true,
fontName: 'allowWriteFilesInBuild-test',
}),
],
});
28 changes: 25 additions & 3 deletions src/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { fileURLToPath } from 'url';
import { readFile } from 'fs/promises';
import { constants } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { readFile, access, rmdir } from 'node:fs/promises';
import { describe, it, beforeAll, afterAll, expect } from 'vitest';
import { build, createServer, preview, normalizePath } from 'vite';
import type { RollupOutput } from 'rollup';
Expand All @@ -16,6 +17,7 @@ const fileURLToNormalizedPath = (url: URL) => normalizePath(fileURLToPath(url));
const enum ConfigType {
Basic = './vite.basic.config.ts',
NoInline = './vite.no-inline.config.ts',
AllowWriteFilesInBuild = './vite.allowWriteFilesInBuild.config.ts',
}
const getConfig = (configType: ConfigType): InlineConfig => ({
logLevel: 'silent',
Expand Down Expand Up @@ -181,10 +183,30 @@ describe('build:no-inline', () => {
});

types.forEach(type => {
it.concurrent(`has font of type ${type} available`, async () => {
it.concurrent.each(types)('has font of type %s available', async () => {
const iconAssetName = output.find(({ fileName }) => fileName.startsWith('assets/iconfont-') && fileName.endsWith(type))!.fileName;
const [expected, res] = await Promise.all([loadFileContent(`fonts/iconfont.${type}`, 'buffer'), fetchBufferContent(server, `/${iconAssetName}`)]);
expect(res).toStrictEqual(expected);
});
});
});

describe('build allowWriteFilesInBuild', () => {
const buildConfig = getConfig(ConfigType.AllowWriteFilesInBuild);

beforeAll(async () => {
await build(buildConfig);
});

afterAll(async () => {
await rmdir(new URL('webfont-test/artifacts', root), { recursive: true });
});

it.concurrent.each([...types, 'html', 'css'])('has generated font of type %s', async type => {
const fileName = `webfont-test/artifacts/allowWriteFilesInBuild-test.${type}`;
const fileNameCasing = types.includes(type) ? fileName : fileName.toLowerCase();
const filePath = new URL(fileNameCasing, root);

await expect(access(filePath, constants.F_OK)).resolves.not.toThrow();
});
});
14 changes: 5 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,20 +55,16 @@ export function viteSvgToWebfont<T extends GeneratedFontTypes = GeneratedFontTyp
if (updateFiles) {
processedOptions.files = parseFiles(options);
}
if (isBuild) {
if (isBuild && !options.allowWriteFilesInBuild) {
processedOptions.writeFiles = false;
}
generatedFonts = await webfontGenerator(processedOptions);
const hasFilesToSave = !processedOptions.writeFiles && (processedOptions.css || processedOptions.html);
if (!isBuild && hasFilesToSave) {
const promises: Promise<void>[] = [];
if (processedOptions.css) {
promises.push(ensureDirExistsAndWriteFile(inline(generatedFonts.generateCss()), processedOptions.cssDest));
}
if (processedOptions.html) {
promises.push(ensureDirExistsAndWriteFile(generatedFonts.generateHtml(), processedOptions.htmlDest));
}
await Promise.all(promises);
await Promise.all([
processedOptions.css && ensureDirExistsAndWriteFile(inline(generatedFonts.generateCss()), processedOptions.cssDest),
processedOptions.html && ensureDirExistsAndWriteFile(generatedFonts.generateHtml(), processedOptions.htmlDest),
]);
}
if (updateFiles) {
const module = _moduleGraph?.getModuleById(resolvedVirtualModuleId);
Expand Down
6 changes: 6 additions & 0 deletions src/optionParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,12 @@ export interface IconPluginOptions<T extends GeneratedFontTypes = GeneratedFontT
* @default false
*/
inline?: boolean;
/**
* Allow outputting assets (HTML, CSS, and Fonts) during build.
* @see {@link https://github.com/atlowChemi/vite-svg-2-webfont/issues/32#issuecomment-2203187501}
* @default false
*/
allowWriteFilesInBuild?: boolean;
}

export function parseIconTypesOption<T extends GeneratedFontTypes = GeneratedFontTypes>({ types }: Pick<IconPluginOptions<T>, 'types'>): T[] {
Expand Down

0 comments on commit f34da69

Please sign in to comment.