-
Notifications
You must be signed in to change notification settings - Fork 11
/
esm-webpack-plugin.js
235 lines (212 loc) · 8.71 KB
/
esm-webpack-plugin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
const ConcatSource = require("webpack-sources").ConcatSource;
const MultiModule = require("webpack/lib/MultiModule");
const Template = require("webpack/lib/Template");
const PLUGIN_NAME = "EsmWebpackPlugin";
const warn = msg => console.warn(`[${PLUGIN_NAME}] ${msg}`);
const IS_JS_FILE = /\.[cm]?js$/i;
const defaultOptions = {
// Exclude non-js files
exclude: fileName => !IS_JS_FILE.test(fileName),
// Skip Nothing
skipModule: () => false,
// Treat externals as globals, by default
moduleExternals: false,
// Add __esModule property to all externals
esModuleExternals: true
};
/**
* Add ESM `export` statements to the bottom of a webpack chunk
* with the exposed exports.
*/
module.exports = class EsmWebpackPlugin {
/**
*
* @param {Object} [options]
* @param {Function} [options.exclude]
* A callback function to evaluate each output file name and determine if it should be
* excluded from being wrapped with ESM exports. By default, all files whose
* file extension is not `.js` or `.mjs` will be excluded.
* The provided callback will receive two input arguments:
* - `{String} fileName`: the file name being evaluated
* - `{Chunk} chunk`: the webpack `chunk` being worked on.
* @param {Function} [options.skipModule]
* A callback function to evaluate each single module in the bundle and if its list of
* exported members should be included.
* @param {boolean} [options.moduleExternals]
* A boolean that determines whether to treat webpack externals as ES modules or not.
* Defaults to false.
*/
constructor(options) {
this._options = {
...defaultOptions,
...options
};
}
apply(compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, compilationTap.bind(this));
}
};
function exportsForModule(module, libVar, pluginOptions) {
let exports = "";
const namedExports = [];
const moduleName = typeof module.nameForCondition === 'function'
? module.nameForCondition()
: undefined;
if (moduleName && pluginOptions.skipModule(moduleName, module)) {
return '';
}
if (module instanceof MultiModule) {
module.dependencies.forEach(dependency => {
exports += exportsForModule(dependency.module, libVar, pluginOptions);
});
} else if (Array.isArray(module.buildMeta.providedExports)) {
module.buildMeta.providedExports.forEach(exportName => {
if (exportName === "default") {
exports += `export default ${libVar}['${exportName}'];\n`
} else {
const scopedExportVarName = `_${libVar}$${exportName}`;
exports += `const ${scopedExportVarName} = ${libVar}['${exportName}'];\n`;
namedExports.push(` ${scopedExportVarName} as ${exportName}`);
}
});
} else {
exports += `export default ${libVar};\nexport { ${libVar} };\n`
}
return `
${
exports.length > 0 && namedExports.length > 0
? `${libVar} === undefined && console.error('esm-webpack-plugin: nothing exported!');`
: ''
}
${exports}${
namedExports.length ?
`\nexport {\n${namedExports.join(",\n")}\n}` :
""
}`;
}
function importsForModule(chunk, pluginOptions) {
if (pluginOptions.moduleExternals) {
const externals = chunk.getModules().filter(m => m.external);
const importStatements = externals.map(m => {
const request = typeof m.request === 'object' ? m.request.amd : m.request;
const identifier = `__WEBPACK_EXTERNAL_MODULE_${Template.toIdentifier(`${m.id}`)}__`;
return pluginOptions.esModuleExternals
? `import * as $${identifier} from '${request}'; var ${identifier} = cloneWithEsModuleProperty($${identifier});`
: `import * as ${identifier} from '${request}';`
})
const result = [importStatements.join("\n")];
if (pluginOptions.esModuleExternals) {
// The code here was originally copied from https://github.com/joeldenning/add-esmodule
result.push(Template.asString([
"\n",
"function cloneWithEsModuleProperty(ns) {",
Template.indent([
"const result = Object.create(null);",
`Object.defineProperty(result, "__esModule", {`,
Template.indent([
`value: true,`,
`enumerable: false,`,
`configurable: true`,
]),
"});",
`const propertyNames = Object.getOwnPropertyNames(ns);`,
`for (let i = 0; i < propertyNames.length; i++) {`,
Template.indent([
`const propertyName = propertyNames[i];`,
`Object.defineProperty(result, propertyName, {`,
Template.indent([
`get: function () {`,
Template.indent([
`return ns[propertyName];`
]),
`},`,
`enumerable: true,`,
`configurable: false,`
]),
`});`
]),
`}`,
`if (Object.getOwnPropertySymbols) {`,
Template.indent([
`const symbols = Object.getOwnPropertySymbols(ns);`,
`for (let i = 0; i < symbols.length; i++) {`,
Template.indent([
`const symbol = symbols[i];`,
`Object.defineProperty(result, symbol, {`,
Template.indent([
`get: function () {`,
Template.indent([
`return ns[symbol];`
]),
`},`,
`enumerable: false,`,
`configurable: false,`,
]),
`});`,
]),
"}",
]),
`}`,
`Object.preventExtensions(result);`,
`Object.seal(result);`,
`if (Object.freeze) {`,
Template.indent([
`Object.freeze(result);`,
]),
`}`,
`return result;`,
]),
`}`
]));
}
result.push("\n");
return result;
} else {
// Use default webpack behavior
return [];
}
}
function compilationTap(compilation) {
const libVar = compilation.outputOptions.library;
const exclude = this._options.exclude;
if (!libVar) {
warn("output.library is expected to be set!");
}
if (
compilation.outputOptions.libraryTarget &&
compilation.outputOptions.libraryTarget !== "var" &&
compilation.outputOptions.libraryTarget !== "assign"
) {
warn(`output.libraryTarget (${compilation.outputOptions.libraryTarget}) expected to be 'var' or 'assign'!`);
}
if (this._options.moduleExternals) {
compilation.hooks.buildModule.tap(PLUGIN_NAME, (module) => {
if (module.external) {
// See https://webpack.js.org/configuration/externals/#externalstype
// We want AMD because it references __WEBPACK_EXTERNAL_MODULE_ instead
// of the raw external request string.
module.externalType = 'amd';
}
});
}
compilation.hooks.optimizeChunkAssets.tapAsync(PLUGIN_NAME, (chunks, done) => {
chunks.forEach(chunk => {
if (chunk.entryModule && chunk.entryModule.buildMeta.providedExports) {
chunk.files.forEach(fileName => {
if (exclude && exclude(fileName, chunk)) {
return;
}
// Add the exports to the bottom of the file (expecting only one file) and
// add that file back to the compilation
compilation.assets[fileName] = new ConcatSource(
...importsForModule(chunk, this._options),
compilation.assets[fileName],
"\n\n",
exportsForModule(chunk.entryModule, libVar, this._options)
);
});
}
});
done();
});
}