-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
71 lines (56 loc) · 1.68 KB
/
index.js
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
const { basename, extname } = require(`path`)
const { compile } = require(`svelte/compiler`)
const through = require(`through2`)
const toPascalCase = require(`just-pascal-case`)
const MagicString = require(`magic-string`)
const defaultExtensions = [ `.html`, `.svelte` ]
const sourceAndMap = (source, mapUrl) => `${ source }\n//# sourceMappingURL=${ mapUrl }`
const TO_REPLACE = `exports.default = `
module.exports = function transformSvelte(file, options) {
let data = ``
const extensionsArray = (options.extensions && options.extensions._) || defaultExtensions
const extension = extname(file)
if (extensionIsInList(extension, extensionsArray)) {
return through(function write(chunk, enc, cb) {
data += chunk
cb()
}, function end(cb) {
const base = basename(file)
const name = toPascalCase(base.replace(extension, ``))
try {
const svelteOptions = Object.assign({}, options.svelte, {
name,
filename: base,
format: `cjs`,
})
delete svelteOptions._
const { js } = compile(data, svelteOptions)
const { code } = js
const magic = new MagicString(code, {
filename: base,
})
const overwriteStart = code.indexOf(TO_REPLACE)
if (overwriteStart !== -1) {
const overwriteEnd = overwriteStart + TO_REPLACE.length
magic.overwrite(overwriteStart, overwriteEnd, `module.exports = `)
}
this.push(
sourceAndMap(
magic.toString(),
magic.generateMap({
source: file,
}).toUrl()
)
)
cb()
} catch (err) {
cb(err)
}
})
} else {
return through()
}
}
function extensionIsInList(extension, extensionsArray) {
return extensionsArray.indexOf(extension.toLowerCase()) !== -1
}