| 1 | /*
|
|---|
| 2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
|---|
| 3 | Author Tobias Koppers @sokra
|
|---|
| 4 | */
|
|---|
| 5 |
|
|---|
| 6 | "use strict";
|
|---|
| 7 |
|
|---|
| 8 | const { fileURLToPath } = require("url");
|
|---|
| 9 | const { NormalModule } = require("..");
|
|---|
| 10 |
|
|---|
| 11 | /** @typedef {import("../Compiler")} Compiler */
|
|---|
| 12 |
|
|---|
| 13 | const PLUGIN_NAME = "FileUriPlugin";
|
|---|
| 14 |
|
|---|
| 15 | class FileUriPlugin {
|
|---|
| 16 | /**
|
|---|
| 17 | * Applies the plugin by registering its hooks on the compiler.
|
|---|
| 18 | * @param {Compiler} compiler the compiler instance
|
|---|
| 19 | * @returns {void}
|
|---|
| 20 | */
|
|---|
| 21 | apply(compiler) {
|
|---|
| 22 | compiler.hooks.compilation.tap(
|
|---|
| 23 | PLUGIN_NAME,
|
|---|
| 24 | (compilation, { normalModuleFactory }) => {
|
|---|
| 25 | normalModuleFactory.hooks.resolveForScheme
|
|---|
| 26 | .for("file")
|
|---|
| 27 | .tap(PLUGIN_NAME, (resourceData) => {
|
|---|
| 28 | const url = new URL(resourceData.resource);
|
|---|
| 29 | const path = fileURLToPath(url);
|
|---|
| 30 | const query = url.search;
|
|---|
| 31 | const fragment = url.hash;
|
|---|
| 32 | resourceData.path = path;
|
|---|
| 33 | resourceData.query = query;
|
|---|
| 34 | resourceData.fragment = fragment;
|
|---|
| 35 | resourceData.resource = path + query + fragment;
|
|---|
| 36 | return true;
|
|---|
| 37 | });
|
|---|
| 38 | const hooks = NormalModule.getCompilationHooks(compilation);
|
|---|
| 39 | hooks.readResource
|
|---|
| 40 | .for(undefined)
|
|---|
| 41 | .tapAsync(PLUGIN_NAME, (loaderContext, callback) => {
|
|---|
| 42 | const { resourcePath } = loaderContext;
|
|---|
| 43 | loaderContext.fs.readFile(resourcePath, (err, result) => {
|
|---|
| 44 | if (err) return callback(err);
|
|---|
| 45 | loaderContext.addDependency(resourcePath);
|
|---|
| 46 | callback(null, result);
|
|---|
| 47 | });
|
|---|
| 48 | });
|
|---|
| 49 | }
|
|---|
| 50 | );
|
|---|
| 51 | }
|
|---|
| 52 | }
|
|---|
| 53 |
|
|---|
| 54 | module.exports = FileUriPlugin;
|
|---|