/
.eleventy.js
96 lines (85 loc) · 2.66 KB
/
.eleventy.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
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
const EleventySvelte = require('./EleventySvelte')
const path = require('path')
const url = require('url')
const defaultOptions = {
assetDir: 'assets',
outputClient: true,
rollupPluginSvelteSSROptions: {},
rollupPluginSvelteClientOptions: {},
rollupClientPlugins: [],
rollupSSRPlugins: [],
}
const svelteComponentRegex = new RegExp(/11ty.svelte$/);
module.exports = function (eleventyConfig, configOptions = {}) {
const options = { ...eleventyConfig, ...defaultOptions, ...configOptions }
const eleventySvelte = new EleventySvelte(options)
eleventyConfig.addTemplateFormats('11ty.svelte')
eleventyConfig.addFilter('svelteData', function (dataFn) {
return `window.__DATA__ = ${typeof dataFn === 'function' ? JSON.stringify(dataFn(this.ctx)) : '{}'}`
})
eleventyConfig.addShortcode('svelteClient', function (id) {
if (!svelteComponentRegex.test(this.page.inputPath)) {
return '';
}
const component = eleventySvelte.getComponent(path.normalize(this.page.inputPath))
return `
<script type="module">
import Component from '${url.format(component.client)}';
new Component({
target: document.getElementById('${id}'),
props: window.__DATA__,
hydrate: true
})
</script>
`
})
eleventyConfig.addShortcode('svelteClientLegacy', function (id) {
if (!svelteComponentRegex.test(this.page.inputPath)) {
return '';
}
const component = eleventySvelte.getComponent(path.normalize(this.page.inputPath))
return `
<script nomodule>
System.import('/${component.clientLegacy}')
.then(c => {
new c.default({
target: document.getElementById('${id}'),
props: window.__DATA__,
hydrate: true
});
});
</script>
`
})
eleventyConfig.addExtension('11ty.svelte', {
read: false, // We use rollup to read the files
getData: true,
init: async function () {
await eleventySvelte.build(this.config.dir.output, this.config.pathPrefix)
},
getInstanceFromInputPath: function (inputPath) {
return eleventySvelte.getComponent(path.normalize(inputPath))
},
compile: function (str, inputPath) {
return (data) => {
if (str) {
// When str has a value, it's being used for permalinks in data
return typeof str === 'function' ? str(data) : str
}
const {
html,
head,
css
} = eleventySvelte.getComponent(path.normalize(inputPath)).ssr.render(data);
return {
html,
head,
css: css.code,
toString() {
return html
}
}
}
},
})
}