webpack/lib/AmdMainTemplatePlugin.js

88 lines
2.0 KiB
JavaScript
Raw Normal View History

/*
2018-07-30 23:08:51 +08:00
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { ConcatSource } = require("webpack-sources");
const Template = require("./Template");
/** @typedef {import("./Compilation")} Compilation */
class AmdMainTemplatePlugin {
/**
* @param {string} name the library name
*/
constructor(name) {
/** @type {string} */
this.name = name;
}
/**
* @param {Compilation} compilation the compilation instance
* @returns {void}
*/
apply(compilation) {
2018-02-25 09:00:20 +08:00
const { mainTemplate, chunkTemplate } = compilation;
const onRenderWithEntry = (source, chunk, hash) => {
2018-02-25 09:00:20 +08:00
const externals = chunk.getModules().filter(m => m.external);
const externalsDepsArray = JSON.stringify(
externals.map(
m => (typeof m.request === "object" ? m.request.amd : m.request)
)
);
const externalsArguments = externals
.map(
m => `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier(`${m.id}`)}__`
)
.join(", ");
if (this.name) {
2017-11-29 01:43:01 +08:00
const name = mainTemplate.getAssetPath(this.name, {
hash,
chunk
});
return new ConcatSource(
2018-03-26 22:56:10 +08:00
`define(${JSON.stringify(
name
)}, ${externalsDepsArray}, function(${externalsArguments}) { return `,
2018-02-25 09:00:20 +08:00
source,
"});"
);
} else if (externalsArguments) {
return new ConcatSource(
2018-03-26 22:56:10 +08:00
`define(${externalsDepsArray}, function(${externalsArguments}) { return `,
2018-02-25 09:00:20 +08:00
source,
"});"
);
} else {
return new ConcatSource("define(function() { return ", source, "});");
}
};
2018-02-25 09:00:20 +08:00
for (const template of [mainTemplate, chunkTemplate]) {
template.hooks.renderWithEntry.tap(
"AmdMainTemplatePlugin",
onRenderWithEntry
);
}
mainTemplate.hooks.globalHashPaths.tap("AmdMainTemplatePlugin", paths => {
if (this.name) {
paths.push(this.name);
}
return paths;
});
mainTemplate.hooks.hash.tap("AmdMainTemplatePlugin", hash => {
hash.update("exports amd");
hash.update(this.name);
});
}
}
module.exports = AmdMainTemplatePlugin;