This repository has been archived by the owner on Oct 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
getOutputPublicPath.ts
105 lines (84 loc) · 2.43 KB
/
getOutputPublicPath.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
// Copyright (c) 2018 Steven Enten. All rights reserved. Licensed under the MIT license.
import * as webpack from 'webpack';
export type GetOutputPublicPathInput = { compilation: webpack.compilation.Compilation }
| webpack.compilation.Compilation
| webpack.Compiler
| webpack.Configuration
| webpack.Output
| string
| null
| undefined;
export interface GetOutputPublicPathOptions {
endsSlash?: boolean;
pathOnly?: boolean;
startsSlash?: boolean;
}
export const GET_OUTPUT_PUBLIC_PATH_OPTIONS_DEFAULT: GetOutputPublicPathOptions = {
endsSlash: false,
pathOnly: true,
startsSlash: true,
};
const URL_BASE_REGEX = /(^\w+:|^)\/\/([^\/]*)/;
export function getOutputPublicPath(
obj: GetOutputPublicPathInput,
options?: GetOutputPublicPathOptions,
) {
options = { ...GET_OUTPUT_PUBLIC_PATH_OPTIONS_DEFAULT, ...options };
let publicPath: string|null = null;
// reduce from highest potential object to webpack config options output
if (obj && typeof obj === 'object') {
// WebpackStats
if ('compilation' in obj && obj.compilation) {
obj = obj.compilation;
}
// WebpackCompilation
if ('compiler' in obj && obj.compiler) {
obj = obj.compiler;
}
// WebpackCompiler
if ('options' in obj && obj.options) {
obj = obj.options;
}
// WebpackConfigOptionsOutput
if ('output' in obj && obj.output) {
obj = obj.output;
}
// WebpackConfigOptionsOutput
if ('publicPath' in obj && obj.publicPath) {
obj = obj.publicPath;
}
}
if (typeof obj === 'string') {
publicPath = obj;
}
if (!publicPath) {
publicPath = '/';
}
if (publicPath !== '/') {
if (options.pathOnly) {
publicPath = publicPath.replace(URL_BASE_REGEX, '');
}
if (!URL_BASE_REGEX.test(publicPath)) {
if (options.startsSlash && !publicPath.startsWith('/')) {
publicPath = '/' + publicPath;
}
if (!options.startsSlash) {
while (publicPath.startsWith('/')) {
publicPath = publicPath.substring(1);
}
}
}
if (options.endsSlash && !publicPath.endsWith('/')) {
publicPath = publicPath + '/';
}
if (!options.endsSlash && publicPath !== '/') {
while (publicPath.endsWith('/')) {
publicPath = publicPath.substring(0, publicPath.length - 1);
}
}
}
if (publicPath === '/' && !options.endsSlash && !options.startsSlash) {
publicPath = '';
}
return publicPath;
}