-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.ts
182 lines (157 loc) · 6.14 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import { Plugin } from '@bundless/cli'
import { NodeResolvePlugin, RewritePlugin } from '@bundless/cli/dist/plugins'
import { osAgnosticPath } from '@bundless/cli/dist/utils'
import { PartialMessage as ESBuildMessage } from 'esbuild'
import { promises as fs } from 'fs'
import { platform } from 'os'
import path from 'path'
import { createMakeHot } from 'svelte-hmr'
import * as compiler from 'svelte/compiler'
import {
CompileOptions,
Warning as SvelteWarning,
} from 'svelte/types/compiler/interfaces'
import { PreprocessorGroup } from 'svelte/types/compiler/preprocess/types'
import { typescriptPreprocessor } from './typescript'
let makeHot = (...args) => {
makeHot = createMakeHot({ walk: compiler.walk })
return makeHot(...args)
}
export function SveltePlugin(options: PluginOptions = {}): Plugin {
let {
compilerOptions = {},
preprocess = [],
typescript = true,
hmrOptions,
} = options
if (typescript) {
preprocess = [typescriptPreprocessor, ...preprocess]
}
return {
name: 'svelte',
modulesToPrebundle: [
'svelte-hmr/runtime/hot-api-esm',
'svelte-hmr/runtime/proxy-adapter-dom',
],
setup(build) {
const {
onLoad,
onResolve,
ctx: { isBuild, graph, config, root },
} = build
NodeResolvePlugin({
extensions: ['.svelte'],
isExtensionRequiredInImportPath: true,
}).setup({
...build,
onResolve,
onLoad() {},
})
if (!isBuild) {
RewritePlugin({ filter: /\.svelte(\?.*)?$/ }).setup(build)
}
let cssMap: Map<string, string> = new Map()
onLoad({ filter: /\.svelte$/i }, async (args) => {
let source = await fs.readFile(args.path, 'utf-8')
let finalCompileOptions: CompileOptions = {
css: false,
generate: config.platform === 'node' ? 'ssr' : 'dom',
...compilerOptions,
dev: !isBuild,
filename: args.path,
outputFilename: args.path,
format: 'esm',
}
if (preprocess.length) {
let processed = await compiler.preprocess(
source,
preprocess,
{
filename: args.path,
},
)
source = processed.code
if (processed.map)
finalCompileOptions.sourcemap = processed.map
}
try {
let compiled = compiler.compile(source, finalCompileOptions)
let { js, css, warnings } = compiled
if (!finalCompileOptions.css && css?.code) {
const cssPath = args.path + '.css'
js.code =
`import "./${path.basename(cssPath)}";\n` + js.code
if (graph) {
// mark css file as a derived file from svelte
graph.ensureEntry(osAgnosticPath(args.path, root), {
computedModules: new Set([
osAgnosticPath(cssPath, root),
]),
})
}
cssMap.set(args.path, css.code)
}
if (!isBuild) {
js.code = makeHot({
id: args.path,
compiledCode: js.code,
hotOptions: {
preserveLocalState: true,
injectCss: true,
...hmrOptions,
absoluteImports: false,
noOverlay: true,
},
compiled: compiled,
originalCode: source,
compileOptions: finalCompileOptions,
})
}
return {
contents: js.code,
warnings: warnings.map(convertMessage),
}
} catch (e) {
return { errors: [convertMessage(e)] }
}
function convertMessage(msg: SvelteWarning): ESBuildMessage {
let { message, start, end } = msg
let location: undefined | ESBuildMessage['location']
if (start && end) {
let lineText = source.split(/\r\n|\r|\n/g)[start.line]
let lineEnd =
start.line == end.line
? end.column
: lineText.length
location = {
file: args.path,
line: start.line,
column: start.column,
length: lineEnd - start.column,
lineText,
}
}
return { text: message, location }
}
})
onResolve({ filter: /\.svelte\.css/i }, async (args) => {
return {
path: path.resolve(args.resolveDir, args.path),
}
})
onLoad({ filter: /\.svelte\.css/i }, ({ path: filename }) => {
filename = filename.replace('.css', '')
let css = cssMap.get(filename)
if (!css) return null
return { contents: css, loader: 'css' }
})
},
}
}
export interface PluginOptions {
compilerOptions?: CompileOptions
preprocess?: PreprocessorGroup[]
hmrOptions?: any
typescript?: boolean
}
export default SveltePlugin