-
Notifications
You must be signed in to change notification settings - Fork 920
/
build-util.ts
228 lines (213 loc) · 6.02 KB
/
build-util.ts
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import type CSSModuleLoader from 'css-modules-loader-core';
import type {EventEmitter} from 'events';
import execa from 'execa';
import {statSync} from 'fs';
import npmRunPath from 'npm-run-path';
import path from 'path';
import {
BuildScript,
SnowpackConfig,
SnowpackPluginBuildArgs,
SnowpackPluginBuildResult,
} from '../config';
const IS_PREACT = /from\s+['"]preact['"]/;
export function checkIsPreact(filePath: string, contents: string) {
return filePath.endsWith('.jsx') && IS_PREACT.test(contents);
}
export function isDirectoryImport(fileLoc: string, spec: string): boolean {
const importedFileOnDisk = path.resolve(path.dirname(fileLoc), spec);
try {
const stat = statSync(importedFileOnDisk);
return stat.isDirectory();
} catch (err) {
// file doesn't exist, that's fine
}
return false;
}
export function wrapImportMeta({
code,
hmr,
env,
config: {buildOptions},
}: {
code: string;
hmr: boolean;
env: boolean;
config: SnowpackConfig;
}) {
if (!code.includes('import.meta')) {
return code;
}
return (
(hmr
? `import * as __SNOWPACK_HMR__ from '/${buildOptions.metaDir}/hmr.js';\nimport.meta.hot = __SNOWPACK_HMR__.createHotContext(import.meta.url);\n`
: ``) +
(env
? `import __SNOWPACK_ENV__ from '/${buildOptions.metaDir}/env.js';\nimport.meta.env = __SNOWPACK_ENV__;\n`
: ``) +
'\n' +
code
);
}
let _cssModuleLoader: CSSModuleLoader;
export async function wrapCssModuleResponse({
url,
code,
ext,
hasHmr = false,
config: {buildOptions},
}: {
url: string;
code: string;
ext: string;
hasHmr?: boolean;
config: SnowpackConfig;
}) {
_cssModuleLoader = _cssModuleLoader || new (require('css-modules-loader-core'))();
const {injectableSource, exportTokens} = await _cssModuleLoader.load(code, url, undefined, () => {
throw new Error('Imports in CSS Modules are not yet supported.');
});
return `${
hasHmr
? `
import * as __SNOWPACK_HMR_API__ from '/${buildOptions.metaDir}/hmr.js';
import.meta.hot = __SNOWPACK_HMR_API__.createHotContext(import.meta.url);
import.meta.hot.accept(({module}) => {
code = module.code;
json = module.default;
});
import.meta.hot.dispose(() => {
document.head.removeChild(styleEl);
});\n`
: ``
}
export let code = ${JSON.stringify(injectableSource)};
let json = ${JSON.stringify(exportTokens)};
export default json;
const styleEl = document.createElement("style");
const codeEl = document.createTextNode(code);
styleEl.type = 'text/css';
styleEl.appendChild(codeEl);
document.head.appendChild(styleEl);`;
}
export function wrapHtmlResponse({
code,
hasHmr = false,
buildOptions,
}: {
code: string;
hasHmr?: boolean;
buildOptions: SnowpackConfig['buildOptions'];
}) {
// replace %PUBLIC_URL% in HTML files (along with surrounding slashes, if any)
code = code.replace(/\/?%PUBLIC_URL%\/?/g, '/');
if (hasHmr) {
code += `<script type="module" src="/${buildOptions.metaDir}/hmr.js"></script>`;
}
return code;
}
export function wrapEsmProxyResponse({
url,
code,
ext,
hasHmr = false,
config: {buildOptions},
}: {
url: string;
code: string;
ext: string;
hasHmr?: boolean;
config: SnowpackConfig;
}) {
if (ext === '.json') {
return `${
hasHmr
? `
import * as __SNOWPACK_HMR_API__ from '/${buildOptions.metaDir}/hmr.js';
import.meta.hot = __SNOWPACK_HMR_API__.createHotContext(import.meta.url);
import.meta.hot.accept(({module}) => {
json = module.default;
});`
: ''
}
let json = ${JSON.stringify(JSON.parse(code))};
export default json;`;
}
if (ext === '.css') {
return `${hasHmr
? `
import * as __SNOWPACK_HMR_API__ from '/${buildOptions.metaDir}/hmr.js';
import.meta.hot = __SNOWPACK_HMR_API__.createHotContext(import.meta.url);
import.meta.hot.accept();
import.meta.hot.dispose(() => {
document.head.removeChild(styleEl);
});\n`
: ''
}
const code = ${JSON.stringify(code)};
const styleEl = document.createElement("style");
const codeEl = document.createTextNode(code);
styleEl.type = 'text/css';
styleEl.appendChild(codeEl);
document.head.appendChild(styleEl);`;
}
return `export default ${JSON.stringify(url)};`;
}
export type FileBuilder = (
args: SnowpackPluginBuildArgs,
) => null | SnowpackPluginBuildResult | Promise<null | SnowpackPluginBuildResult>;
export function getFileBuilderForWorker(
cwd: string,
selectedWorker: BuildScript,
messageBus: EventEmitter,
): FileBuilder | undefined {
const {id, type, cmd, plugin} = selectedWorker;
if (type !== 'build') {
throw new Error(`scripts[${id}] is not a build script.`);
}
if (plugin?.build) {
const buildFn = plugin.build;
return async (args: SnowpackPluginBuildArgs) => {
try {
const result = await buildFn(args);
return result;
} catch (err) {
messageBus.emit('WORKER_MSG', {id, level: 'error', msg: err.message});
messageBus.emit('WORKER_UPDATE', {id, state: ['ERROR', 'red']});
return null;
}
};
}
return async ({contents, filePath}: SnowpackPluginBuildArgs) => {
let cmdWithFile = cmd.replace('$FILE', filePath);
try {
const {stdout, stderr} = await execa.command(cmdWithFile, {
env: npmRunPath.env(),
extendEnv: true,
shell: true,
input: contents,
cwd,
});
if (stderr) {
messageBus.emit('WORKER_MSG', {id, level: 'warn', msg: `${filePath}\n${stderr}`});
}
return {result: stdout};
} catch (err) {
messageBus.emit('WORKER_MSG', {id, level: 'error', msg: `${filePath}\n${err.stderr}`});
messageBus.emit('WORKER_UPDATE', {id, state: ['ERROR', 'red']});
return null;
}
};
}
const PUBLIC_ENV_REGEX = /^SNOWPACK_PUBLIC_/;
export function generateEnvModule(mode: 'development' | 'production') {
const envObject = {...process.env};
for (const env of Object.keys(envObject)) {
if (!PUBLIC_ENV_REGEX.test(env)) {
delete envObject[env];
}
}
envObject.MODE = mode;
envObject.NODE_ENV = mode;
return `export default ${JSON.stringify(envObject)};`;
}