forked from codesandbox/codesandbox-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloader.ts
More file actions
96 lines (82 loc) · 2.68 KB
/
loader.ts
File metadata and controls
96 lines (82 loc) · 2.68 KB
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
import postcss, { ProcessOptions } from 'postcss';
import postcssImportPlugin from 'postcss-import';
import { join } from 'path';
import { isDependencyPath } from 'sandbox/eval/utils/is-dependency-path';
import TranspiledModule, { LoaderContext } from '../../transpiled-module';
async function resolveCSSFile(
loaderContext: LoaderContext,
path: string,
basePath: string
): Promise<TranspiledModule> {
const isDependency = isDependencyPath(path);
if (isDependency) {
// First try to resolve the package.json, in case it has a style field
try {
const pkgJson = await loaderContext.resolveTranspiledModuleAsync(
join(path, 'package.json')
);
const parsedPkg = JSON.parse(pkgJson.module.code);
if (parsedPkg.style) {
const fullPath = join(path, parsedPkg.style);
return loaderContext.resolveTranspiledModuleAsync(fullPath);
}
} catch (e) {
/* Move to step 2 */
}
return loaderContext.resolveTranspiledModuleAsync(path);
}
const fullPath = path.charAt(0) === '/' ? path : join(basePath, path);
return loaderContext.resolveTranspiledModuleAsync(fullPath);
}
export default function(
code: string,
loaderContext: LoaderContext
): Promise<{ transpiledCode: string; sourceMap: any }> {
return new Promise((resolve, reject) => {
const plugins = [
postcssImportPlugin({
resolve: async (id: string, root: string) => {
try {
const result = await resolveCSSFile(loaderContext, id, root);
return result.module.path;
} catch (e) {
return null;
}
},
load: async (filename: string) => {
const tModule = await loaderContext.resolveTranspiledModuleAsync(
filename
);
return tModule.module.code;
},
}),
];
const options: ProcessOptions = {
to: loaderContext.path,
from: loaderContext.path,
map: {
inline: true,
annotation: true,
},
};
return (
postcss(plugins)
// Explcitly give undefined if code is null, otherwise postcss crashses
.process(code === null ? undefined : code, options)
.then(result => {
if (result.messages) {
const messages = result.messages as any[];
messages.forEach(m => {
if (m.type === 'dependency') {
loaderContext.addDependency(m.file);
}
});
}
const map = result.map && result.map.toJSON();
resolve({ transpiledCode: result.css, sourceMap: map });
return null; // silence bluebird warning
})
.catch(err => reject(err))
);
});
}