-
Notifications
You must be signed in to change notification settings - Fork 609
/
Copy pathindex.ts
74 lines (65 loc) · 2.45 KB
/
index.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
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
/**
* This simple loader wraps the loading of CSS in script equivalent to
* require("\@microsoft/load-themed-styles").loadStyles('... css text ...').
* @packageDocumentation
*/
import type { LoaderContext, PitchLoaderDefinitionFunction } from 'webpack';
const defaultThemedStylesPath: string = require.resolve('@microsoft/load-themed-styles');
/**
* Options for the loader.
*
* @public
*/
export interface ILoadThemedStylesLoaderOptions {
/**
* If this parameter is set to "true," the "loadAsync" parameter is set to true in the call to loadStyles.
* Defaults to false.
*/
async?: boolean;
loadThemedStylesPath?: string;
esModule?: boolean;
}
/**
* This simple loader wraps the loading of CSS in script equivalent to
* require("load-themed-styles").loadStyles('... css text ...').
*
* @public
*/
// eslint-disable-next-line func-style
export const pitch: PitchLoaderDefinitionFunction<ILoadThemedStylesLoaderOptions> = function (
this: LoaderContext<ILoadThemedStylesLoaderOptions>,
remainingRequest: string
): string {
const loaderContext: LoaderContext<ILoadThemedStylesLoaderOptions> = this;
const options: ILoadThemedStylesLoaderOptions = loaderContext.getOptions() || {};
if ((options as Record<string, unknown>).namedExport) {
throw new Error('The "namedExport" option has been removed.');
}
const { async = false, loadThemedStylesPath = defaultThemedStylesPath, esModule = false } = options;
const stringifiedRequest: string = JSON.stringify(
loaderContext.utils.contextify(loaderContext.context, '!!' + remainingRequest)
);
const importCode: [contentImport: string, loaderImport: string] = esModule
? [
`import content from ${stringifiedRequest};`,
`import { loadStyles } from ${JSON.stringify(loadThemedStylesPath)};`
]
: [
`var content = require(${stringifiedRequest});`,
`var loader = require(${JSON.stringify(loadThemedStylesPath)});`
];
return [
...importCode,
'',
'if(typeof content === "string") content = [[module.id, content]];',
'',
'// add the styles to the DOM',
`for (var i = 0; i < content.length; i++) ${
esModule ? 'loadStyles' : 'loader.loadStyles'
}(content[i][1], ${async === true});`,
'',
'if(content.locals) module.exports = content.locals;'
].join('\n');
};