Skip to content

Commit 7fc8df0

Browse files
author
Brijesh Bittu
committed
Add a separate option for runtimePackages
This is different that corePackages options which is supposed to be transformed by Pigment. runtimePackages option can be used by user to implement their own runtime version of Pigment.
1 parent 3ae3644 commit 7fc8df0

File tree

1 file changed

+123
-109
lines changed

1 file changed

+123
-109
lines changed

packages/pigment-css-plugin/src/unplugin.ts

Lines changed: 123 additions & 109 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ type BundlerConfig = Omit<PigmentConfig, 'themeArgs'> & {
2626
include?: FilterPattern;
2727
exclude?: FilterPattern;
2828
theme?: Theme;
29+
runtimePackages?: string[];
2930
corePackages?: string[];
3031
transformSx?: boolean;
3132
nextJsOptions?: {
@@ -42,7 +43,14 @@ type BundlerConfig = Omit<PigmentConfig, 'themeArgs'> & {
4243
postTransform?: (result: Result, fileName: string, cssFilename: string) => Promise<void>;
4344
};
4445

45-
const DEFAULT_CORE_PACKAGES = ['@pigment-css/core', '@pigment-css/react-new'];
46+
const DEFAULT_RUNTIME_PACKAGES = [
47+
'@pigment-css/core',
48+
'@pigment-css/react-new',
49+
// this is required for apps in the current workspace
50+
'pigment-css-core',
51+
'pigment-css-react-new',
52+
'pigment-css-react',
53+
];
4654
const VIRTUAL_CSS_FILE = `\0pigment-runtime-styles.css`;
4755
const VIRTUAL_THEME_FILE = `\0pigment-runtime-theme.js`;
4856

@@ -134,6 +142,7 @@ export const plugin = createUnplugin<BundlerConfig>((options, meta) => {
134142
outputCss = true,
135143
theme = {},
136144
corePackages = [],
145+
runtimePackages: optRuntimePackages = [],
137146
debug = false,
138147
transformSx = true,
139148
nextJsOptions,
@@ -148,7 +157,7 @@ export const plugin = createUnplugin<BundlerConfig>((options, meta) => {
148157
...rest
149158
} = options;
150159
const filter = createFilter(include, exclude);
151-
const runtimePackages = Array.from(new Set(DEFAULT_CORE_PACKAGES.concat(corePackages)));
160+
const runtimePackages = Array.from(new Set(DEFAULT_RUNTIME_PACKAGES.concat(optRuntimePackages)));
152161
const cssFileLookup = nextJsOptions ? globalCssFileLookup : new Map<string, string>();
153162
const baseName = `${process.env.PACKAGE_NAME}/${meta.framework}`;
154163
const cache = new TransformCacheCollection();
@@ -185,7 +194,8 @@ export const plugin = createUnplugin<BundlerConfig>((options, meta) => {
185194
},
186195
transform(_code, id) {
187196
if (id.endsWith('styles.css')) {
188-
return generateCssFromTheme('vars' in theme ? theme.vars : theme);
197+
const res = generateCssFromTheme('vars' in theme ? theme.vars : theme);
198+
return res;
189199
}
190200
if (id.includes('theme')) {
191201
return 'export default {}';
@@ -230,7 +240,7 @@ export const plugin = createUnplugin<BundlerConfig>((options, meta) => {
230240
plugins.push(
231241
getSxBabelUnplugin({
232242
name: `${baseName}/sx`,
233-
finalTransformLibraries: runtimePackages,
243+
finalTransformLibraries: corePackages,
234244
filter,
235245
}),
236246
);
@@ -250,12 +260,9 @@ export const plugin = createUnplugin<BundlerConfig>((options, meta) => {
250260
configResolved(resolvedConfig: ResolvedViteConfig) {
251261
projectPath = resolvedConfig.root;
252262
},
253-
configureServer() {
254-
// do stuff related to hot reloads.
255-
},
256263
},
257264
transformInclude(id) {
258-
return isZeroRuntimeProcessableFile(id.split('?', 1)[0], runtimePackages) && filter(id);
265+
return isZeroRuntimeProcessableFile(id.split('?', 1)[0], corePackages) && filter(id);
259266
},
260267
async transform(code, url) {
261268
const [filePath] = url.split('?', 1);
@@ -278,120 +285,127 @@ export const plugin = createUnplugin<BundlerConfig>((options, meta) => {
278285
'babel-plugin-define-var',
279286
...(rest.babelOptions?.plugins ?? []),
280287
].filter(Boolean);
281-
const result = await wywTransform(
282-
{
283-
options: {
284-
filename,
285-
root: projectPath,
286-
// @TODO - Handle RTL processing
287-
preprocessor: basePreProcessor,
288-
pluginOptions: {
289-
...rest,
290-
// @ts-ignore WyW does not identify this property
291-
themeArgs: {
292-
theme: 'vars' in theme ? theme : themeWithVars,
293-
},
294-
features: {
295-
useWeakRefInEval: false,
296-
...rest.features,
297-
},
298-
babelOptions: {
299-
...rest.babelOptions,
300-
plugins: babelPlugins,
301-
presets: !(filename.endsWith('ts') || filename.endsWith('tsx'))
302-
? Array.from(presets)
303-
: Array.from(presets).concat('@babel/preset-typescript'),
304-
},
305-
overrideContext(context, file) {
306-
if (!context.$RefreshSig$) {
307-
context.$RefreshSig$ = outerNoop;
308-
}
309-
if (overrideContext) {
310-
return overrideContext(context, file);
311-
}
312-
313-
return context;
314-
},
315-
tagResolver(source: string, tag: string) {
316-
const tagResult = tagResolver?.(source, tag);
317-
if (tagResult) {
318-
return tagResult;
319-
}
320-
return null;
288+
289+
try {
290+
const result = await wywTransform(
291+
{
292+
options: {
293+
filename,
294+
root: projectPath,
295+
// @TODO - Handle RTL processing
296+
preprocessor: basePreProcessor,
297+
pluginOptions: {
298+
...rest,
299+
// @ts-ignore WyW does not identify this property
300+
themeArgs: {
301+
theme: themeWithVars,
302+
},
303+
features: {
304+
useWeakRefInEval: false,
305+
...rest.features,
306+
},
307+
babelOptions: {
308+
...rest.babelOptions,
309+
plugins: babelPlugins,
310+
presets:
311+
filename.endsWith('ts') || filename.endsWith('tsx')
312+
? Array.from(presets).concat('@babel/preset-typescript')
313+
: Array.from(presets),
314+
},
315+
overrideContext(context, file) {
316+
if (!context.$RefreshSig$) {
317+
context.$RefreshSig$ = outerNoop;
318+
}
319+
if (overrideContext) {
320+
return overrideContext(context, file);
321+
}
322+
323+
return context;
324+
},
325+
tagResolver(source: string, tag: string) {
326+
const tagResult = tagResolver?.(source, tag);
327+
if (tagResult) {
328+
return tagResult;
329+
}
330+
return null;
331+
},
321332
},
322333
},
334+
cache,
335+
eventEmitter: emitter,
323336
},
324-
cache,
325-
eventEmitter: emitter,
326-
},
327-
code,
328-
asyncResolver,
329-
);
337+
code,
338+
asyncResolver,
339+
);
330340

331-
if (typeof result.cssText !== 'string') {
332-
return null;
333-
}
341+
if (typeof result.cssText !== 'string') {
342+
return null;
343+
}
334344

335-
if (!outputCss) {
336-
return {
337-
code: result.code,
338-
map: result.sourceMap,
339-
};
340-
}
345+
if (!outputCss) {
346+
return {
347+
code: result.code,
348+
map: result.sourceMap,
349+
};
350+
}
341351

342-
if (nextJsOptions && result.cssText.includes('url(')) {
343-
result.cssText = await handleUrlReplacement(
344-
result.cssText,
345-
filename,
346-
asyncResolver,
347-
projectPath,
348-
);
349-
}
352+
if (nextJsOptions && result.cssText.includes('url(')) {
353+
result.cssText = await handleUrlReplacement(
354+
result.cssText,
355+
filename,
356+
asyncResolver,
357+
projectPath,
358+
);
359+
}
350360

351-
if (sourceMap && result.cssSourceMapText) {
352-
const map = Buffer.from(result.cssSourceMapText).toString('base64');
353-
result.cssText += `/*# sourceMappingURL=data:application/json;base64,${map}*/`;
354-
}
361+
if (sourceMap && result.cssSourceMapText) {
362+
const map = Buffer.from(result.cssSourceMapText).toString('base64');
363+
result.cssText += `/*# sourceMappingURL=data:application/json;base64,${map}*/`;
364+
}
355365

356-
if (nextJsOptions) {
357-
const data = `${nextJsOptions.placeholderCssFile}?${btoa(
358-
encodeURI(
359-
encodeURIComponent(
360-
JSON.stringify({
361-
filename: filename.split(path.sep).pop(),
362-
source: result.cssText,
363-
}),
366+
if (nextJsOptions) {
367+
const data = `${nextJsOptions.placeholderCssFile}?${btoa(
368+
encodeURI(
369+
encodeURIComponent(
370+
JSON.stringify({
371+
filename: filename.split(path.sep).pop(),
372+
source: result.cssText,
373+
}),
374+
),
364375
),
365-
),
366-
)}`;
376+
)}`;
377+
return {
378+
// CSS import should be the last so that nested components produce correct CSS order injection.
379+
code: `${result.code}\nimport ${JSON.stringify(data)};`,
380+
map: result.sourceMap,
381+
};
382+
}
383+
const cssFilename = path
384+
.normalize(`${filename.replace(/\.[jt]sx?$/, '')}.virtual.pigment.css`)
385+
.replace(/\\/g, path.posix.sep);
386+
387+
const cssRelativePath = path
388+
.relative(projectPath, cssFilename)
389+
.replace(/\\/g, path.posix.sep);
390+
// Starting with null character so that it calls the resolver method (resolveId in line:430)
391+
// Otherwise, webpack tries to resolve the path directly
392+
const cssId = `\0${cssRelativePath}`;
393+
394+
cssFileLookup.set(cssId, result.cssText);
395+
result.code += `\nimport ${JSON.stringify(cssId)};`;
396+
397+
if (postTransform) {
398+
await postTransform.call(this, result, filename, cssId);
399+
}
400+
367401
return {
368-
// CSS import should be the last so that nested components produce correct CSS order injection.
369-
code: `${result.code}\nimport ${JSON.stringify(data)};`,
402+
code: result.code,
370403
map: result.sourceMap,
371404
};
405+
} catch (ex) {
406+
console.error(ex);
407+
throw ex;
372408
}
373-
const cssFilename = path
374-
.normalize(`${filename.replace(/\.[jt]sx?$/, '')}.virtual.pigment.css`)
375-
.replace(/\\/g, path.posix.sep);
376-
377-
const cssRelativePath = path
378-
.relative(projectPath, cssFilename)
379-
.replace(/\\/g, path.posix.sep);
380-
// Starting with null character so that it calls the resolver method (resolveId in line:430)
381-
// Otherwise, webpack tries to resolve the path directly
382-
const cssId = `\0${cssRelativePath}`;
383-
384-
cssFileLookup.set(cssId, result.cssText);
385-
result.code += `\nimport ${JSON.stringify(cssId)};`;
386-
387-
if (postTransform) {
388-
await postTransform.call(this, result, filename, cssId);
389-
}
390-
391-
return {
392-
code: result.code,
393-
map: result.sourceMap,
394-
};
395409
},
396410
};
397411

0 commit comments

Comments
 (0)