UNPKG

1.8 kBJavaScriptView Raw
1/*
2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Author Sergey Melyukov @smelukov
4*/
5
6"use strict";
7
8const { RawSource } = require("webpack-sources");
9const Generator = require("../Generator");
10const RuntimeGlobals = require("../RuntimeGlobals");
11
12/** @typedef {import("webpack-sources").Source} Source */
13/** @typedef {import("../Generator").GenerateContext} GenerateContext */
14/** @typedef {import("../NormalModule")} NormalModule */
15
16const TYPES = new Set(["javascript"]);
17
18class AssetSourceGenerator extends Generator {
19 /**
20 * @param {NormalModule} module module for which the code should be generated
21 * @param {GenerateContext} generateContext context for generate
22 * @returns {Source} generated code
23 */
24 generate(module, { chunkGraph, runtimeTemplate, runtimeRequirements }) {
25 runtimeRequirements.add(RuntimeGlobals.module);
26
27 const originalSource = module.originalSource();
28
29 if (!originalSource) {
30 return new RawSource("");
31 }
32
33 const content = originalSource.source();
34
35 let encodedSource;
36 if (typeof content === "string") {
37 encodedSource = content;
38 } else {
39 encodedSource = content.toString("utf-8");
40 }
41 return new RawSource(
42 `${RuntimeGlobals.module}.exports = ${JSON.stringify(encodedSource)};`
43 );
44 }
45
46 /**
47 * @param {NormalModule} module fresh module
48 * @returns {Set<string>} available types (do not mutate)
49 */
50 getTypes(module) {
51 return TYPES;
52 }
53
54 /**
55 * @param {NormalModule} module the module
56 * @param {string=} type source type
57 * @returns {number} estimate size of the module
58 */
59 getSize(module, type) {
60 const originalSource = module.originalSource();
61
62 if (!originalSource) {
63 return 0;
64 }
65
66 // Example: m.exports="abcd"
67 return originalSource.size() + 12;
68 }
69}
70
71module.exports = AssetSourceGenerator;