-
Notifications
You must be signed in to change notification settings - Fork 336
Add esbuild-plugin #14
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
Merged
Merged
Changes from all commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
10ca6cf
Experiment
mattcompiles c12f486
Progress
mattcompiles 5c226c3
Merge branch 'master' into esbuild
mattcompiles d22f068
Progress
mattcompiles 9cdc27d
Esbuild start fixture working
mattcompiles b1c1452
Merge branch 'master' into esbuild
mattcompiles 18cf293
Add stylesheet tests
mattcompiles ac2d02a
Document esbuild plugin
mattcompiles b506059
Remove old files
mattcompiles f22d342
Remove unused deps
mattcompiles 8adfbd7
Add projectRoot option
mattcompiles 5cf0235
Update setup readme
mattcompiles 64a5fad
Clean up
mattcompiles 3f61cd2
Update README.md
mattcompiles 93e34d7
Handle missing dist folder
mattcompiles 4c6df16
Update README.md
mattcompiles 917dc17
Removed unneeded build option
mattcompiles 3946497
Add esbuild runtime option
mattcompiles aa07519
Fix fileScope plugin
mattcompiles d4d5eea
Fix filescoping
mattcompiles a125f4c
Address PR comments
mattcompiles File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| { | ||
| "name": "@vanilla-extract/esbuild-plugin", | ||
| "version": "0.0.1", | ||
markdalgleish marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| "description": "Zero-runtime Stylesheets-in-TypeScript", | ||
| "main": "dist/vanilla-extract-esbuild-plugin.cjs.js", | ||
| "module": "dist/vanilla-extract-esbuild-plugin.esm.js", | ||
| "files": [ | ||
| "/dist" | ||
| ], | ||
| "repository": { | ||
| "type": "git", | ||
| "url": "https://github.com/seek-oss/vanilla-extract.git", | ||
| "directory": "packages/esbuild-plugin" | ||
| }, | ||
| "author": "SEEK", | ||
| "license": "MIT", | ||
| "peerDependencies": { | ||
| "esbuild": ">=0.11.1" | ||
| }, | ||
| "dependencies": { | ||
| "@vanilla-extract/css": "^0.1.0", | ||
| "chalk": "^4.1.0", | ||
| "dedent": "^0.7.0", | ||
| "eval": "^0.1.6", | ||
| "javascript-stringify": "^2.0.1", | ||
| "lodash": "^4.17.21" | ||
| }, | ||
| "devDependencies": { | ||
| "@types/dedent": "^0.7.0", | ||
| "esbuild": "^0.11.1" | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,214 @@ | ||
| import { dirname, relative } from 'path'; | ||
| import { promises as fs } from 'fs'; | ||
|
|
||
| import type { Adapter } from '@vanilla-extract/css'; | ||
| import { setAdapter } from '@vanilla-extract/css/adapter'; | ||
| import { transformCss } from '@vanilla-extract/css/transformCss'; | ||
| import dedent from 'dedent'; | ||
| import { build as esbuild, Plugin } from 'esbuild'; | ||
| // @ts-expect-error | ||
| import evalCode from 'eval'; | ||
| import { stringify } from 'javascript-stringify'; | ||
| import isPlainObject from 'lodash/isPlainObject'; | ||
|
|
||
| const vanillaExtractPath = dirname( | ||
| require.resolve('@vanilla-extract/css/package.json'), | ||
| ); | ||
|
|
||
| const vanillaCssNamespace = 'vanilla-extract-css-ns'; | ||
|
|
||
| interface FilescopePluginOptions { | ||
| projectRoot?: string; | ||
| } | ||
| const vanillaExtractFilescopePlugin = ({ | ||
| projectRoot, | ||
| }: FilescopePluginOptions): Plugin => ({ | ||
| name: 'vanilla-extract-filescope', | ||
| setup(build) { | ||
| build.onLoad({ filter: /\.(js|jsx|ts|tsx)$/ }, async ({ path }) => { | ||
| const originalSource = await fs.readFile(path, 'utf-8'); | ||
|
|
||
| if ( | ||
| path.indexOf(vanillaExtractPath) === -1 && | ||
| originalSource.indexOf('@vanilla-extract/css/fileScope') === -1 | ||
| ) { | ||
| const fileScope = projectRoot ? relative(projectRoot, path) : path; | ||
|
|
||
| const contents = ` | ||
| import { setFileScope, endFileScope } from "@vanilla-extract/css/fileScope"; | ||
| setFileScope("${fileScope}"); | ||
| ${originalSource} | ||
| endFileScope() | ||
| `; | ||
|
|
||
| return { | ||
| contents, | ||
| resolveDir: dirname(path), | ||
| }; | ||
| } | ||
| }); | ||
| }, | ||
| }); | ||
|
|
||
| interface VanillaExtractPluginOptions { | ||
| outputCss?: boolean; | ||
| externals?: Array<string>; | ||
| projectRoot?: string; | ||
| runtime?: boolean; | ||
| } | ||
| export function vanillaExtractPlugin({ | ||
| outputCss = true, | ||
| externals = [], | ||
| projectRoot, | ||
| runtime = false, | ||
| }: VanillaExtractPluginOptions = {}): Plugin { | ||
| if (runtime) { | ||
| // If using runtime CSS then just apply fileScopes to code | ||
| return vanillaExtractFilescopePlugin({ projectRoot }); | ||
| } | ||
|
|
||
| return { | ||
| name: 'vanilla-extract', | ||
| setup(build) { | ||
| build.onResolve({ filter: /vanilla\.css\?source=.*$/ }, (args) => { | ||
| return { | ||
| path: args.path, | ||
| namespace: vanillaCssNamespace, | ||
| }; | ||
| }); | ||
|
|
||
| build.onLoad( | ||
| { filter: /.*/, namespace: vanillaCssNamespace }, | ||
| ({ path }) => { | ||
| const [, source] = path.match(/\?source=(.*)$/) ?? []; | ||
|
|
||
| if (!source) { | ||
| throw new Error('No source in vanilla CSS file'); | ||
| } | ||
|
|
||
| return { | ||
| contents: Buffer.from(source, 'base64').toString('utf-8'), | ||
| loader: 'css', | ||
| }; | ||
| }, | ||
| ); | ||
|
|
||
| build.onLoad({ filter: /\.css\.(js|jsx|ts|tsx)$/ }, async ({ path }) => { | ||
| const result = await esbuild({ | ||
| entryPoints: [path], | ||
| metafile: true, | ||
| bundle: true, | ||
| external: ['@vanilla-extract', ...externals], | ||
| platform: 'node', | ||
| write: false, | ||
| plugins: [vanillaExtractFilescopePlugin({ projectRoot })], | ||
| }); | ||
|
|
||
| const { outputFiles } = result; | ||
|
|
||
| if (!outputFiles || outputFiles.length !== 1) { | ||
| throw new Error('Invalid child compilation'); | ||
| } | ||
|
|
||
| type Css = Parameters<Adapter['appendCss']>[0]; | ||
| const cssByFileScope = new Map<string, Array<Css>>(); | ||
| const localClassNames = new Set<string>(); | ||
|
|
||
| const cssAdapter: Adapter = { | ||
| appendCss: (css, fileScope) => { | ||
| if (outputCss) { | ||
| const fileScopeCss = cssByFileScope.get(fileScope) ?? []; | ||
|
|
||
| fileScopeCss.push(css); | ||
|
|
||
| cssByFileScope.set(fileScope, fileScopeCss); | ||
| } | ||
| }, | ||
| registerClassName: (className) => { | ||
| localClassNames.add(className); | ||
| }, | ||
| onEndFileScope: () => {}, | ||
| }; | ||
|
|
||
| setAdapter(cssAdapter); | ||
mattcompiles marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| const sourceWithBoundLoaderInstance = `require('@vanilla-extract/css/adapter').setAdapter(__adapter__);${outputFiles[0].text}`; | ||
|
|
||
| const evalResult = evalCode( | ||
| sourceWithBoundLoaderInstance, | ||
| path, | ||
| { console, __adapter__: cssAdapter }, | ||
| true, | ||
| ); | ||
|
|
||
| const cssRequests = []; | ||
|
|
||
| for (const [fileScope, fileScopeCss] of cssByFileScope) { | ||
| const css = transformCss({ | ||
| localClassNames: Array.from(localClassNames), | ||
| cssObjs: fileScopeCss, | ||
| }).join('\n'); | ||
| const base64Css = Buffer.from(css, 'utf-8').toString('base64'); | ||
|
|
||
| cssRequests.push(`${fileScope}.vanilla.css?source=${base64Css}`); | ||
| } | ||
|
|
||
| const contents = serializeVanillaModule(cssRequests, evalResult); | ||
|
|
||
| return { | ||
| contents, | ||
| loader: 'js', | ||
| }; | ||
| }); | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| const stringifyExports = (value: any) => | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. More just marking this for future conversation, but this makes me think it might be good to have a more first-class integration API so stuff like this is handled for you. |
||
| stringify( | ||
| value, | ||
| (value, _indent, next) => { | ||
| const valueType = typeof value; | ||
| if ( | ||
| valueType === 'string' || | ||
| valueType === 'number' || | ||
| valueType === 'undefined' || | ||
| value === null || | ||
| Array.isArray(value) || | ||
| isPlainObject(value) | ||
| ) { | ||
| return next(value); | ||
| } | ||
|
|
||
| throw new Error(dedent` | ||
| Invalid exports. | ||
|
|
||
| You can only export plain objects, arrays, strings, numbers and null/undefined. | ||
| `); | ||
| }, | ||
| 0, | ||
| { | ||
| references: true, // Allow circular references | ||
| maxDepth: Infinity, | ||
| maxValues: Infinity, | ||
| }, | ||
| ); | ||
|
|
||
| const serializeVanillaModule = ( | ||
| cssRequests: Array<string>, | ||
| exports: Record<string, unknown>, | ||
| ) => { | ||
| const cssImports = cssRequests.map((request) => { | ||
| return `import '${request}';`; | ||
| }); | ||
|
|
||
| const moduleExports = Object.keys(exports).map((key) => | ||
| key === 'default' | ||
| ? `export default ${stringifyExports(exports[key])};` | ||
| : `export var ${key} = ${stringifyExports(exports[key])};`, | ||
| ); | ||
|
|
||
| const outputCode = [...cssImports, ...moduleExports]; | ||
|
|
||
| return outputCode.join('\n'); | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,6 @@ | ||
| export * from './startFixture'; | ||
| export * from './getNodeStyles'; | ||
| export * from './getStylesheet'; | ||
|
|
||
| export const getTestNodes = (fixture: string) => | ||
| require(`@fixtures/${fixture}/test-nodes.json`); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| import path from 'path'; | ||
| import { existsSync, promises as fs } from 'fs'; | ||
|
|
||
| import { vanillaExtractPlugin } from '@vanilla-extract/esbuild-plugin'; | ||
| import { serve } from 'esbuild'; | ||
|
|
||
| import { TestServer } from './types'; | ||
|
|
||
| export interface EsbuildFixtureOptions { | ||
| type: 'esbuild' | 'esbuild-runtime'; | ||
| mode?: 'development' | 'production'; | ||
| port: number; | ||
| } | ||
| export const startEsbuildFixture = async ( | ||
| fixtureName: string, | ||
| { type, mode = 'development', port = 3000 }: EsbuildFixtureOptions, | ||
| ): Promise<TestServer> => { | ||
| const entry = require.resolve(`@fixtures/${fixtureName}`); | ||
| const projectRoot = path.dirname( | ||
| require.resolve(`@fixtures/${fixtureName}/package.json`), | ||
| ); | ||
| const outdir = path.join(projectRoot, 'dist'); | ||
|
|
||
| if (existsSync(outdir)) { | ||
| await fs.rm(outdir, { recursive: true }); | ||
| } | ||
|
|
||
| await fs.mkdir(outdir); | ||
|
|
||
| const server = await serve( | ||
| { servedir: outdir, port }, | ||
| { | ||
| entryPoints: [entry], | ||
| metafile: true, | ||
| platform: 'browser', | ||
| bundle: true, | ||
| minify: mode === 'production', | ||
| plugins: [ | ||
| vanillaExtractPlugin({ | ||
| projectRoot, | ||
| runtime: type === 'esbuild-runtime', | ||
| }), | ||
| ], | ||
| outdir, | ||
| define: { | ||
| 'process.env.NODE_ENV': JSON.stringify(mode), | ||
| }, | ||
| }, | ||
| ); | ||
|
|
||
| await fs.writeFile( | ||
| path.join(outdir, 'index.html'), | ||
| ` | ||
| <!DOCTYPE html> | ||
| <html lang="en"> | ||
| <head> | ||
| <meta charset="utf-8"> | ||
| <title>esbuild - ${fixtureName}</title> | ||
| <link rel="stylesheet" type="text/css" href="index.css" /> | ||
| </head> | ||
| <body> | ||
| <script src="index.js"></script> | ||
| </body> | ||
| </html> | ||
| `, | ||
| ); | ||
|
|
||
| return { | ||
| type: 'esbuild', | ||
| url: `http://localhost:${port}`, | ||
| close: () => { | ||
| server.stop(); | ||
|
|
||
| return Promise.resolve(); | ||
| }, | ||
| }; | ||
| }; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.