Skip to content
This repository was archived by the owner on Jul 6, 2025. It is now read-only.

Commit 5959777

Browse files
committed
refactor: post-compile inline styles in compiler module
1 parent bae1e05 commit 5959777

File tree

3 files changed

+52
-37
lines changed

3 files changed

+52
-37
lines changed

compiler/mod.ts

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { ensureDir, path } from '../deps.ts'
22
import { existsFileSync } from '../shared/fs.ts'
33
import log from '../shared/log.ts'
4+
import type { LoaderPlugin } from '../types.ts'
45
import { VERSION } from '../version.ts'
56
import { checksum } from './dist/wasm-checksum.js'
67
import init, { transformSync } from './dist/wasm-pack.js'
@@ -27,15 +28,18 @@ export type TransformOptions = {
2728
transpileOnly?: boolean
2829
bundleMode?: boolean
2930
bundleExternal?: string[]
31+
// loaders for inline styles transform
32+
loaders?: LoaderPlugin[]
3033
}
3134

3235
export type TransformResult = {
3336
code: string
3437
deps: DependencyDescriptor[]
35-
inlineStyles: Record<string, { type: string, quasis: string[], exprs: string[] }>
3638
map?: string
3739
}
3840

41+
type InlineStyles = Record<string, { type: string, quasis: string[], exprs: string[] }>
42+
3943
type DependencyDescriptor = {
4044
specifier: string
4145
isDynamic: boolean
@@ -106,7 +110,44 @@ export async function transform(url: string, code: string, options: TransformOpt
106110
if (t !== null) {
107111
log.debug(`init compiler wasm in ${Math.round(performance.now() - t)}ms`)
108112
}
109-
return transformSync(url, code, options)
113+
114+
const { loaders, ...transformOptions } = options
115+
let { code: jsContent, inlineStyles, deps, map } = transformSync(url, code, transformOptions)
116+
117+
// resolve inline-style
118+
await Promise.all(Object.entries(inlineStyles as InlineStyles).map(async ([key, style]) => {
119+
let tpl = style.quasis.reduce((tpl, quais, i, a) => {
120+
tpl += quais
121+
if (i < a.length - 1) {
122+
tpl += `%%aleph-inline-style-expr-${i}%%`
123+
}
124+
return tpl
125+
}, '')
126+
.replace(/\:\s*%%aleph-inline-style-expr-(\d+)%%/g, (_, id) => `: var(--aleph-inline-style-expr-${id})`)
127+
.replace(/%%aleph-inline-style-expr-(\d+)%%/g, (_, id) => `/*%%aleph-inline-style-expr-${id}%%*/`)
128+
if (style.type !== 'css' && loaders !== undefined) {
129+
for (const loader of loaders) {
130+
if (loader.test.test(`.${style.type}`)) {
131+
const { code, type } = await loader.transform({ url, content: (new TextEncoder).encode(tpl) })
132+
if (type === 'css') {
133+
tpl = code
134+
break
135+
}
136+
}
137+
}
138+
}
139+
// todo: postcss and minify
140+
tpl = tpl.replace(
141+
/\: var\(--aleph-inline-style-expr-(\d+)\)/g,
142+
(_, id) => ': ${' + style.exprs[parseInt(id)] + '}'
143+
).replace(
144+
/\/\*%%aleph-inline-style-expr-(\d+)%%\*\//g,
145+
(_, id) => '${' + style.exprs[parseInt(id)] + '}'
146+
)
147+
jsContent = jsContent.replace(`"%%${key}-placeholder%%"`, '`' + tpl + '`')
148+
}))
149+
150+
return { code: jsContent, deps, map }
110151
}
111152

112153
/**

server/app.ts

Lines changed: 3 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import type { Config, LoaderPlugin, LoaderTransformResult, ModuleOptions, Router
1212
import { VERSION } from '../version.ts'
1313
import { Bundler } from './bundler.ts'
1414
import { defaultConfig, loadConfig } from './config.ts'
15-
import { clearCompilation, computeHash, createHtml, formatBytesWithColor, getAlephPkgUri, getRelativePath, reFullVersion, reHashJs, reHashResolve, toLocalUrl, trimModuleExt } from './helper.ts'
15+
import { clearCompilation, computeHash, createHtml, formatBytesWithColor, getAlephPkgUri, getRelativePath, isLoaderPlugin, reFullVersion, reHashJs, reHashResolve, toLocalUrl, trimModuleExt } from './helper.ts'
1616

1717
/** A module includes the compilation details. */
1818
export type Module = {
@@ -730,13 +730,14 @@ export class Application implements ServerApplication {
730730
}
731731

732732
const t = performance.now()
733-
const { code, map, deps, inlineStyles } = await transform(url, sourceCode, {
733+
const { code, map, deps } = await transform(url, sourceCode, {
734734
...this.defaultCompileOptions,
735735
swcOptions: {
736736
target: 'es2020',
737737
sourceType
738738
},
739739
sourceMap: this.isDev,
740+
loaders: this.config.plugins.filter(isLoaderPlugin)
740741
})
741742

742743
fsync = true
@@ -745,39 +746,6 @@ export class Application implements ServerApplication {
745746
jsSourceMap = map
746747
}
747748

748-
// resolve inline-style
749-
await Promise.all(Object.entries(inlineStyles).map(async ([key, style]) => {
750-
let tpl = style.quasis.reduce((tpl, quais, i, a) => {
751-
tpl += quais
752-
if (i < a.length - 1) {
753-
tpl += `%%aleph-inline-style-expr-${i}%%`
754-
}
755-
return tpl
756-
}, '')
757-
.replace(/\:\s*%%aleph-inline-style-expr-(\d+)%%/g, (_, id) => `: var(--aleph-inline-style-expr-${id})`)
758-
.replace(/%%aleph-inline-style-expr-(\d+)%%/g, (_, id) => `/*%%aleph-inline-style-expr-${id}%%*/`)
759-
if (style.type !== 'css') {
760-
for (const plugin of this.config.plugins) {
761-
if (plugin.type === 'loader' && plugin.test.test(`.${style.type}`)) {
762-
const { code, type } = await plugin.transform({ url, content: (new TextEncoder).encode(tpl) })
763-
if (type === 'css') {
764-
tpl = code
765-
break
766-
}
767-
}
768-
}
769-
}
770-
// todo: postcss and minify
771-
tpl = tpl.replace(
772-
/\: var\(--aleph-inline-style-expr-(\d+)\)/g,
773-
(_, id) => ': ${' + style.exprs[parseInt(id)] + '}'
774-
).replace(
775-
/\/\*%%aleph-inline-style-expr-(\d+)%%\*\//g,
776-
(_, id) => '${' + style.exprs[parseInt(id)] + '}'
777-
)
778-
jsContent = jsContent.replace(`"%%${key}-placeholder%%"`, '`' + tpl + '`')
779-
}))
780-
781749
mod.deps = deps.map(({ specifier, isDynamic }) => {
782750
const dep: DependencyDescriptor = { url: specifier, hash: '' }
783751
if (isDynamic) {

server/helper.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { colors, createHash, path } from '../deps.ts'
22
import { existsDirSync } from '../shared/fs.ts'
33
import { moduleExts } from '../shared/constants.ts'
44
import util from '../shared/util.ts'
5+
import type { Plugin, LoaderPlugin } from '../types.ts'
56
import { VERSION } from '../version.ts'
67

78
export const reLocaleID = /^[a-z]{2}(-[a-zA-Z0-9]+)?$/
@@ -42,6 +43,11 @@ export const AlephRuntimeCode = `
4243
});
4344
`
4445

46+
/** check the plugin whether is a loader plugin. */
47+
export function isLoaderPlugin(plugin: Plugin): plugin is LoaderPlugin {
48+
return plugin.type === 'loader'
49+
}
50+
4551
/** get aleph pkg uri. */
4652
export function getAlephPkgUri() {
4753
const DEV_PORT = Deno.env.get('ALEPH_DEV_PORT')

0 commit comments

Comments
 (0)