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 |
|
---|
10 | /** @typedef {import("../Compiler")} Compiler */
|
---|
11 |
|
---|
12 | // data URL scheme: "data:text/javascript;charset=utf-8;base64,some-string"
|
---|
13 | // http://www.ietf.org/rfc/rfc2397.txt
|
---|
14 | const URIRegEx = /^data:([^;,]+)?((?:;[^;,]+)*?)(?:;(base64))?,(.*)$/i;
|
---|
15 |
|
---|
16 | const decodeDataURI = uri => {
|
---|
17 | const match = URIRegEx.exec(uri);
|
---|
18 | if (!match) return null;
|
---|
19 |
|
---|
20 | const isBase64 = match[3];
|
---|
21 | const body = match[4];
|
---|
22 | return isBase64
|
---|
23 | ? Buffer.from(body, "base64")
|
---|
24 | : Buffer.from(decodeURIComponent(body), "ascii");
|
---|
25 | };
|
---|
26 |
|
---|
27 | class DataUriPlugin {
|
---|
28 | /**
|
---|
29 | * Apply the plugin
|
---|
30 | * @param {Compiler} compiler the compiler instance
|
---|
31 | * @returns {void}
|
---|
32 | */
|
---|
33 | apply(compiler) {
|
---|
34 | compiler.hooks.compilation.tap(
|
---|
35 | "DataUriPlugin",
|
---|
36 | (compilation, { normalModuleFactory }) => {
|
---|
37 | normalModuleFactory.hooks.resolveForScheme
|
---|
38 | .for("data")
|
---|
39 | .tap("DataUriPlugin", resourceData => {
|
---|
40 | const match = URIRegEx.exec(resourceData.resource);
|
---|
41 | if (match) {
|
---|
42 | resourceData.data.mimetype = match[1] || "";
|
---|
43 | resourceData.data.parameters = match[2] || "";
|
---|
44 | resourceData.data.encoding = match[3] || false;
|
---|
45 | resourceData.data.encodedContent = match[4] || "";
|
---|
46 | }
|
---|
47 | });
|
---|
48 | NormalModule.getCompilationHooks(compilation)
|
---|
49 | .readResourceForScheme.for("data")
|
---|
50 | .tap("DataUriPlugin", resource => decodeDataURI(resource));
|
---|
51 | }
|
---|
52 | );
|
---|
53 | }
|
---|
54 | }
|
---|
55 |
|
---|
56 | module.exports = DataUriPlugin;
|
---|