webpack/lib/AmdMainTemplatePlugin.js

113 lines
2.7 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 ExternalModule = require("./ExternalModule");
const Template = require("./Template");
/** @typedef {import("./Compilation")} Compilation */
/**
* @typedef {Object} AmdMainTemplatePluginOptions
* @param {string=} name the library name
* @property {boolean=} requireAsWrapper
*/
class AmdMainTemplatePlugin {
/**
* @param {AmdMainTemplatePluginOptions} options the plugin options
*/
constructor(options) {
if (!options || typeof options === "string") {
this.name = options;
this.requireAsWrapper = false;
} else {
this.name = options.name;
this.requireAsWrapper = options.requireAsWrapper;
}
}
/**
* @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) => {
const chunkGraph = compilation.chunkGraph;
const modules = chunkGraph
.getChunkModules(chunk)
.filter(m => m instanceof ExternalModule);
const externals = /** @type {ExternalModule[]} */ (modules);
2018-02-25 09:00:20 +08:00
const externalsDepsArray = JSON.stringify(
2019-02-05 17:06:32 +08:00
externals.map(m =>
2019-02-06 22:37:11 +08:00
typeof m.request === "object" && !Array.isArray(m.request)
? m.request.amd
: m.request
2018-02-25 09:00:20 +08:00
)
);
const externalsArguments = externals
.map(
m =>
`__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier(
`${chunkGraph.getModuleId(m)}`
)}__`
2018-02-25 09:00:20 +08:00
)
.join(", ");
if (this.requireAsWrapper) {
return new ConcatSource(
`require(${externalsDepsArray}, function(${externalsArguments}) { return `,
source,
"});"
);
} else 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-11-02 22:39:51 +08:00
mainTemplate.hooks.renderWithEntry.tap(
"AmdMainTemplatePlugin",
onRenderWithEntry
);
chunkTemplate.hooks.renderWithEntry.tap(
"AmdMainTemplatePlugin",
onRenderWithEntry
);
mainTemplate.hooks.hash.tap("AmdMainTemplatePlugin", hash => {
hash.update("exports amd");
2018-09-25 20:45:30 +08:00
if (this.name) {
hash.update(this.name);
}
});
}
}
module.exports = AmdMainTemplatePlugin;