UNPKG

1.35 kBJavaScriptView Raw
1/*
2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Author Tobias Koppers @sokra
4*/
5"use strict";
6
7const { ConcatSource } = require("webpack-sources");
8
9/** @typedef {import("./Compilation")} Compilation */
10
11/**
12 * @param {string[]} accessor the accessor to convert to path
13 * @returns {string} the path
14 */
15const accessorToObjectAccess = accessor => {
16 return accessor.map(a => `[${JSON.stringify(a)}]`).join("");
17};
18
19class ExportPropertyMainTemplatePlugin {
20 /**
21 * @param {string|string[]} property the name of the property to export
22 */
23 constructor(property) {
24 this.property = property;
25 }
26
27 /**
28 * @param {Compilation} compilation the compilation instance
29 * @returns {void}
30 */
31 apply(compilation) {
32 const { mainTemplate, chunkTemplate } = compilation;
33
34 const onRenderWithEntry = (source, chunk, hash) => {
35 const postfix = `${accessorToObjectAccess([].concat(this.property))}`;
36 return new ConcatSource(source, postfix);
37 };
38
39 for (const template of [mainTemplate, chunkTemplate]) {
40 template.hooks.renderWithEntry.tap(
41 "ExportPropertyMainTemplatePlugin",
42 onRenderWithEntry
43 );
44 }
45
46 mainTemplate.hooks.hash.tap("ExportPropertyMainTemplatePlugin", hash => {
47 hash.update("export property");
48 hash.update(`${this.property}`);
49 });
50 }
51}
52
53module.exports = ExportPropertyMainTemplatePlugin;