forked from sveltejs/svelte
-
Notifications
You must be signed in to change notification settings - Fork 0
/
register.js
56 lines (44 loc) · 1.3 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
49
50
51
52
53
54
55
56
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, warnings } = compile(fs.readFileSync(filename, 'utf-8'), options);
if (options.dev) {
warnings.forEach(warning => {
console.warn(`\nSvelte Warning in ${warning.filename}:`);
console.warn(warning.message);
console.warn(warning.frame);
})
}
return module._compile(js.code, filename);
};
}
registerExtension('.svelte');
registerExtension('.html');
module.exports = register;