forked from open-wc/open-wc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebpack-import-meta-loader.js
More file actions
57 lines (47 loc) · 1.54 KB
/
Copy pathwebpack-import-meta-loader.js
File metadata and controls
57 lines (47 loc) · 1.54 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
/* eslint-disable */
// @ts-nocheck
const toBrowserPath = require('./src/to-browser-path');
const regex = /import\.meta/g;
/**
* Webpack loader to rewrite `import.meta` in modules with url data to the source code file location.
*
* @example
* return import.meta;
* // becomes: return ({ url: `${window.location.protocol}//${window.location.host}/relative/path/to/file.js` });
*
* return import.meta.url;
* // becomes: return ({ url: `${window.location.protocol}//${window.location.host}/relative/path/to/file.js` }).url;
*/
module.exports = function(source) {
const path = require('path');
const relativePath = this.context.substring(
this.context.indexOf(this.rootContext) + this.rootContext.length + 1,
this.resource.lastIndexOf(path.sep) + 1,
);
const browserPath = toBrowserPath(relativePath);
const fileName = this.resource.substring(this.resource.lastIndexOf(path.sep) + 1);
let found = false;
let rewrittenSource = source.replace(regex, () => {
found = true;
return `({ url: getAbsoluteUrl('${browserPath}/${fileName}') })`;
});
if (found) {
return `
function getAbsoluteUrl(relativeUrl) {
const publicPath = __webpack_public_path__;
let url = '';
if (!publicPath || publicPath.indexOf('://') < 0) {
url += window.location.protocol + '//' + window.location.host;
}
if (publicPath) {
url += publicPath;
} else {
url += '//';
}
return url + relativeUrl;
}
${rewrittenSource}`;
} else {
return source;
}
};