| 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 NormalModule = require("../NormalModule");
|
|---|
| 9 | const { URIRegEx, decodeDataURI } = require("../util/dataURL");
|
|---|
| 10 |
|
|---|
| 11 | /** @typedef {import("../Compiler")} Compiler */
|
|---|
| 12 |
|
|---|
| 13 | const PLUGIN_NAME = "DataUriPlugin";
|
|---|
| 14 |
|
|---|
| 15 | class DataUriPlugin {
|
|---|
| 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("data")
|
|---|
| 27 | .tap(PLUGIN_NAME, (resourceData, resolveData) => {
|
|---|
| 28 | const match = URIRegEx.exec(resourceData.resource);
|
|---|
| 29 | if (match) {
|
|---|
| 30 | resourceData.data.mimetype = match[1] || "";
|
|---|
| 31 | resourceData.data.parameters = match[2] || "";
|
|---|
| 32 | resourceData.data.encoding = /** @type {"base64" | false} */ (
|
|---|
| 33 | match[3] || false
|
|---|
| 34 | );
|
|---|
| 35 | resourceData.data.encodedContent = match[4] || "";
|
|---|
| 36 | }
|
|---|
| 37 | // Inherit the issuer's resolution context so any nested
|
|---|
| 38 | // dependencies discovered while parsing the data URI's body
|
|---|
| 39 | // (e.g. `url(...)` / `@import` inside an inline CSS data
|
|---|
| 40 | // URI) resolve relative to where the URI was referenced
|
|---|
| 41 | // from, instead of against the synthetic `data:.../` path
|
|---|
| 42 | // that `getContext("data:…")` would otherwise infer.
|
|---|
| 43 | if (
|
|---|
| 44 | resourceData.context === undefined &&
|
|---|
| 45 | resolveData.context !== undefined
|
|---|
| 46 | ) {
|
|---|
| 47 | resourceData.context = resolveData.context;
|
|---|
| 48 | }
|
|---|
| 49 | });
|
|---|
| 50 |
|
|---|
| 51 | NormalModule.getCompilationHooks(compilation)
|
|---|
| 52 | .readResourceForScheme.for("data")
|
|---|
| 53 | .tap(PLUGIN_NAME, (resource) => decodeDataURI(resource));
|
|---|
| 54 | }
|
|---|
| 55 | );
|
|---|
| 56 | }
|
|---|
| 57 | }
|
|---|
| 58 |
|
|---|
| 59 | module.exports = DataUriPlugin;
|
|---|