Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: svg optimization with esm #4526

Merged
merged 1 commit into from
Jun 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
124 changes: 124 additions & 0 deletions packages/qwik-city/buildtime/vite/image-jsx.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import type { OutputFormat } from 'vite-imagetools';
import type { PluginOption } from 'vite';
import { optimize } from 'svgo';
import fs from 'node:fs';
import { parseId } from 'packages/qwik/src/optimizer/src/plugins/plugin';

/**
* @public
*/
export function imagePlugin(): PluginOption[] {
const supportedExtensions = ['jpg', 'jpeg', 'png', 'webp', 'gif', 'avif', 'tiff'].map(
(ext) => `.${ext}?jsx`
);
return [
import('vite-imagetools').then(({ imagetools }) =>
imagetools({
extendOutputFormats(builtins) {
const jsx: OutputFormat = () => (metadatas) => {
const srcSet = metadatas.map((meta) => `${meta.src} ${meta.width}w`).join(', ');
let largestImage: any;
let largestImageSize = 0;
for (let i = 0; i < metadatas.length; i++) {
const m = metadatas[i] as any;
if (m.width > largestImageSize) {
largestImage = m;
largestImageSize = m.width;
}
}
return {
srcSet,
width: largestImage === null || largestImage === void 0 ? void 0 : largestImage.width,
height:
largestImage === null || largestImage === void 0 ? void 0 : largestImage.height,
};
};
return {
...builtins,
jsx,
};
},
defaultDirectives: (url) => {
if (url.searchParams.has('jsx')) {
return new URLSearchParams({
format: 'webp',
quality: '75',
w: '200;400;800;1200',
as: 'jsx',
});
}
return new URLSearchParams();
},
})
),
{
name: 'qwik-city-image',
load: {
order: 'pre',
handler: async (id) => {
if (id.endsWith('.svg?jsx')) {
const code = await fs.promises.readFile(parseId(id).pathId, 'utf-8');
return {
code,
moduleSideEffects: false,
};
}
},
},
transform: (code, id) => {
id = id.toLowerCase();
if (id.endsWith('?jsx')) {
if (supportedExtensions.some((ext) => id.endsWith(ext))) {
return code.replace(
/export default.*/g,
`
import { _jsxQ } from '@builder.io/qwik';
const PROPS = {decoding: 'async', loading: 'lazy', srcSet, width, height};
export default function (props, key, _, dev) {
return _jsxQ('img', props, PROPS, undefined, 3, key, dev);
}`
);
} else if (id.endsWith('.svg?jsx')) {
const svgAttributes: Record<string, string> = {};
const data = optimize(code, {
plugins: [
{
name: 'preset-default',
params: {
overrides: {
removeViewBox: false,
},
},
},
{
name: 'customPluginName',
fn: () => {
return {
element: {
exit: (node) => {
if (node.name === 'svg') {
node.name = 'g';
Object.assign(svgAttributes, node.attributes);
node.attributes = {};
}
},
},
};
},
},
],
}).data;
svgAttributes.dangerouslySetInnerHTML = data.slice(3, -3);
return `
import { _jsxQ } from '@builder.io/qwik';
const PROPS = ${JSON.stringify(svgAttributes)};
export default function (props, key, _, dev) {
return _jsxQ('svg', props, PROPS, undefined, 3, key, dev);
}`;
}
}
return null;
},
},
];
}
65 changes: 3 additions & 62 deletions packages/qwik-city/buildtime/vite/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createMdxTransformer, type MdxTransform } from '../markdown/mdx';
import { basename, join, resolve } from 'node:path';
import type { Plugin, PluginOption, UserConfig } from 'vite';
import type { Plugin, PluginOption, UserConfig, Rollup } from 'vite';
import { loadEnv } from 'vite';
import { generateQwikCityPlan } from '../runtime-generation/generate-qwik-city-plan';
import type { BuildContext } from '../types';
Expand All @@ -19,79 +19,20 @@ import {
generateServiceWorkerRegister,
prependManifestToServiceWorker,
} from '../runtime-generation/generate-service-worker';
import type { Rollup } from 'vite';
import {
NOT_FOUND_PATHS_ID,
RESOLVED_NOT_FOUND_PATHS_ID,
RESOLVED_STATIC_PATHS_ID,
STATIC_PATHS_ID,
} from '../../adapters/shared/vite';
import { postBuild } from '../../adapters/shared/vite/post-build';
import type { OutputFormat } from 'vite-imagetools';
import { imagePlugin } from './image-jsx';

/**
* @public
*/
export function qwikCity(userOpts?: QwikCityVitePluginOptions): PluginOption[] {
return [
qwikCityPlugin(userOpts),
import('vite-imagetools').then(({ imagetools }) =>
imagetools({
extendOutputFormats(builtins) {
const jsx: OutputFormat = () => (metadatas) => {
const srcSet = metadatas.map((meta) => `${meta.src} ${meta.width}w`).join(', ');
let largestImage: any;
let largestImageSize = 0;
for (let i = 0; i < metadatas.length; i++) {
const m = metadatas[i] as any;
if (m.width > largestImageSize) {
largestImage = m;
largestImageSize = m.width;
}
}
return {
srcSet,
width: largestImage === null || largestImage === void 0 ? void 0 : largestImage.width,
height:
largestImage === null || largestImage === void 0 ? void 0 : largestImage.height,
};
};
return {
...builtins,
jsx,
};
},
defaultDirectives: (url) => {
if (url.searchParams.has('jsx')) {
return new URLSearchParams({
format: 'webp',
quality: '75',
w: '200;400;800;1200',
as: 'jsx',
});
}
return new URLSearchParams();
},
})
),
{
name: 'qwik-city-image',
transform: (code, id) => {
if (id.endsWith('?jsx')) {
return code.replace(
/export default.*/g,
`
import { _jsxQ } from '@builder.io/qwik';
const PROPS = {decoding: 'async', loading: 'lazy', srcSet, width, height};
export default function (props, key, _, dev) {
return _jsxQ('img', props, PROPS, undefined, 3, key, dev);
}`
);
}
return null;
},
},
];
return [qwikCityPlugin(userOpts), ...imagePlugin()];
}

function qwikCityPlugin(userOpts?: QwikCityVitePluginOptions): any {
Expand Down
1 change: 1 addition & 0 deletions packages/qwik-city/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
"@mdx-js/mdx": "2.3.0",
"@types/mdx": "2.0.5",
"source-map": "0.7.4",
"svgo": "^3.0.2",
"vfile": "5.3.7",
"vite-imagetools": "^5.0.4",
"zod": "^3.21.4"
Expand Down