forked from sveltejs/svelte
-
Notifications
You must be signed in to change notification settings - Fork 0
/
register.js
48 lines (37 loc) · 1.1 KB
/
register.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
const fs = require('fs');
const path = require('path');
const { compile } = require('./compiler.js');
const extensions = ['.svelte', '.html'];
let compileOptions = {};
function capitalise(name) {
return name[0].toUpperCase() + name.slice(1);
}
function register(options = {}) {
if (options.extensions) {
extensions.forEach(deregisterExtension);
options.extensions.forEach(registerExtension);
}
compileOptions = Object.assign({}, options);
delete compileOptions.extensions;
}
function deregisterExtension(extension) {
delete require.extensions[extension];
}
function registerExtension(extension) {
require.extensions[extension] = function(module, filename) {
const name = path.parse(filename).name
.replace(/^\d/, '_$&')
.replace(/[^a-zA-Z0-9_$]/g, '');
const options = Object.assign({}, compileOptions, {
filename,
name: capitalise(name),
generate: 'ssr',
format: 'cjs'
});
const { js } = compile(fs.readFileSync(filename, 'utf-8'), options);
return module._compile(js.code, filename);
};
}
registerExtension('.svelte');
registerExtension('.html');
module.exports = register;