|
| 1 | +import path from 'path'; |
| 2 | +import { SnowpackBuildMap, SnowpackConfig, SnowpackPlugin } from 'snowpack'; |
| 3 | +import { |
| 4 | + processVanillaFile, |
| 5 | + compile, |
| 6 | + getSourceFromVirtualCssFile, |
| 7 | +} from '@vanilla-extract/integration'; |
| 8 | + |
| 9 | +export default function vanillaExtractPlugin( |
| 10 | + snowpackConfig: SnowpackConfig, |
| 11 | +): SnowpackPlugin { |
| 12 | + const importedByMap = new Map(); |
| 13 | + |
| 14 | + function addImportsToMap(filePath: string, dependency: string) { |
| 15 | + const importedBy = importedByMap.get(dependency); |
| 16 | + if (importedBy) { |
| 17 | + importedBy.add(filePath); |
| 18 | + } else { |
| 19 | + importedByMap.set(dependency, new Set([filePath])); |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + return { |
| 24 | + name: '@vanilla-extract/snowpack-plugin', |
| 25 | + resolve: { |
| 26 | + input: ['.css.ts'], |
| 27 | + output: ['.js', '.css'], |
| 28 | + }, |
| 29 | + onChange({ filePath }) { |
| 30 | + if (importedByMap.has(filePath)) { |
| 31 | + const importedBy = importedByMap.get(filePath); |
| 32 | + importedByMap.delete(filePath); |
| 33 | + for (const dependentFilePath of importedBy) { |
| 34 | + this.markChanged?.(dependentFilePath); |
| 35 | + } |
| 36 | + } |
| 37 | + }, |
| 38 | + async load(args) { |
| 39 | + const { filePath, isSSR } = args; |
| 40 | + const cwd = snowpackConfig.root || process.cwd(); |
| 41 | + |
| 42 | + const { source, watchFiles } = await compile({ |
| 43 | + filePath, |
| 44 | + cwd, |
| 45 | + }); |
| 46 | + |
| 47 | + watchFiles.forEach((dependency) => { |
| 48 | + addImportsToMap(filePath, dependency); |
| 49 | + }); |
| 50 | + |
| 51 | + let css; |
| 52 | + const js = processVanillaFile({ |
| 53 | + source, |
| 54 | + filePath, |
| 55 | + outputCss: !isSSR, |
| 56 | + serializeVirtualCssPath({ base64Source, fileScope }) { |
| 57 | + const cssUrl = `${path.join(cwd, fileScope.filePath)}.css`; |
| 58 | + |
| 59 | + if (cssUrl === `${filePath}.css`) { |
| 60 | + css = getSourceFromVirtualCssFile(`?source=${base64Source}`).source; |
| 61 | + // snowpack injects the .css import for us |
| 62 | + return ''; |
| 63 | + } |
| 64 | + |
| 65 | + const rel = path.relative(path.dirname(filePath), cssUrl); |
| 66 | + const relWithLeadingDot = |
| 67 | + rel.startsWith('./') || rel.startsWith('../') ? rel : `./${rel}`; |
| 68 | + |
| 69 | + return `import "${relWithLeadingDot}";`; |
| 70 | + }, |
| 71 | + }); |
| 72 | + |
| 73 | + const buildMap: SnowpackBuildMap = { |
| 74 | + '.js': { |
| 75 | + code: js, |
| 76 | + }, |
| 77 | + }; |
| 78 | + if (!isSSR && css) { |
| 79 | + buildMap['.css'] = { code: css }; |
| 80 | + } |
| 81 | + return buildMap; |
| 82 | + }, |
| 83 | + }; |
| 84 | +} |
0 commit comments