This repository has been archived by the owner on Mar 20, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
116 lines (99 loc) · 2.6 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
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
import * as path from 'path';
import { compile, preprocess, walk } from 'svelte/compiler';
import { createMakeHot } from 'svelte-hmr';
import rollupSveltePlugin from 'rollup-plugin-svelte';
import { push, componentize } from './utils.js';
let hotApiPath = path.dirname(require.resolve('svelte-hmr/runtime'));
let RE_SVELTE_EXT = /\.svelte$/i;
/** @type {() => import('vite').Plugin} */
export function svelte (opts = {}) {
let {
compilerOptions,
preprocess: preprocessOpts,
hmrOptions = {},
pluginOptions = {},
} = opts;
let {
resolveSvelteField = true,
hotApiMount = '/@@svelte-hmr'
} = pluginOptions;
// Force the path to end with a slash, making it a directory, needed for
// the aliasing to work.
hotApiMount = path.join(hotApiMount, '/');
let makeHot = hmrOptions && createMakeHot({
walk,
hotApi: path.join(hotApiMount, 'hot-api-esm.js'),
adapter: path.join(hotApiMount, 'proxy-adapter-dom.js'),
});
// incredibly dirty hack to make vite resolve the svelte field first before
// any other field like module and main
if (resolveSvelteField) {
try {
let { mainFields } = require('vite/dist/node/resolver');
mainFields.unshift('svelte');
} catch {}
}
return {
// prod build
rollupInputOptions: {
plugins: [
rollupSveltePlugin({
dev: false,
...compilerOptions,
preprocess: preprocessOpts,
include: RE_SVELTE_EXT,
format: 'esm',
generate: 'dom',
emitCss: true,
}),
],
},
// dev
configureServer: [({ config }) => {
// optimized deps
let prevOptimizeDeps = config.optimizeDeps || {};
config.optimizeDeps = {
...prevOptimizeDeps,
include: prevOptimizeDeps.include || [],
exclude: prevOptimizeDeps.exclude || [],
};
push(config.optimizeDeps.include, [
'svelte',
'svelte/internal',
'svelte/store',
'svelte/animate',
'svelte/easing',
'svelte/motion',
'svelte/transition',
]);
}],
alias: {
[hotApiMount]: hotApiPath,
},
transforms: [{
test: (ctx) => !ctx.isBuild && RE_SVELTE_EXT.test(ctx.path),
transform: async ({ path: filename, code }) => {
if (preprocessOpts) {
let result = await preprocess(code, preprocessOpts, { filename });
code = result.code;
}
let compiled = compile(code, {
dev: true,
...compilerOptions,
filename,
name: componentize(filename),
format: 'esm',
generate: 'dom',
})
let result = compiled.js.code;
if (hmrOptions) {
result = makeHot(filename, result, {
...hmrOptions,
compatVite: true,
}, compiled, code, true);
}
return { code: result };
},
}],
};
}