webpack/lib/BaseURIPlugin.js

68 lines
1.5 KiB
JavaScript
Raw Normal View History

2020-08-05 05:42:29 +08:00
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Ivan Kopeykin @vankop
*/
"use strict";
const RuntimeGlobals = require("./RuntimeGlobals");
const SimpleRuntimeModule = require("./SimpleRuntimeModule");
2020-08-05 05:42:29 +08:00
/** @typedef {import("../declarations/WebpackOptions").Target} Target */
/** @typedef {import("./Compiler")} Compiler */
class BaseURIPlugin {
/**
* @param {string=} baseURISource baseURI source
2020-08-05 05:42:29 +08:00
*/
constructor(baseURISource) {
this.baseURISource = baseURISource;
2020-08-05 05:42:29 +08:00
}
/**
* @param {Compiler} compiler compiler
*/
apply(compiler) {
let baseURISource = this.baseURISource;
if (!baseURISource) {
const target = compiler.options.target;
switch (target) {
case "webworker":
baseURISource = "self.location";
break;
case "node":
case "async-node":
case "node-webkit":
case "electron-main":
case "electron-preload":
baseURISource = "require('url').pathToFileURL(__filename)";
break;
case "web":
case "electron-renderer":
baseURISource = "document.baseURI";
break;
}
}
if (!baseURISource) return;
2020-08-05 05:42:29 +08:00
compiler.hooks.compilation.tap("BaseURIPlugin", compilation => {
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.baseURI)
.tap("BaseURIPlugin", chunk => {
2020-08-05 05:42:29 +08:00
compilation.addRuntimeModule(
chunk,
new SimpleRuntimeModule(
"baseURI",
RuntimeGlobals.baseURI,
baseURISource
)
2020-08-05 05:42:29 +08:00
);
});
});
}
}
module.exports = BaseURIPlugin;