1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | "use strict";
|
7 |
|
8 | const NormalModule = require("../NormalModule");
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
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 |
|
30 |
|
31 |
|
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;
|