webpack/lib/dependencies/HarmonyDetectionParserPlugi...

84 lines
2.3 KiB
JavaScript
Raw Normal View History

/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
2018-07-30 23:08:51 +08:00
"use strict";
const HarmonyCompatibilityDependency = require("./HarmonyCompatibilityDependency");
module.exports = class HarmonyDetectionParserPlugin {
apply(parser) {
2018-02-25 09:00:20 +08:00
parser.hooks.program.tap("HarmonyDetectionParserPlugin", ast => {
const isStrictHarmony = parser.state.module.type === "javascript/esm";
2018-02-25 09:00:20 +08:00
const isHarmony =
isStrictHarmony ||
ast.body.some(
statement =>
statement.type === "ImportDeclaration" ||
statement.type === "ExportDefaultDeclaration" ||
statement.type === "ExportNamedDeclaration" ||
statement.type === "ExportAllDeclaration"
2019-01-04 03:39:52 +08:00
);
2018-02-25 09:00:20 +08:00
if (isHarmony) {
const module = parser.state.module;
const compatDep = new HarmonyCompatibilityDependency();
compatDep.loc = {
start: {
line: -1,
column: 0
},
end: {
line: -1,
column: 0
},
index: -3
};
module.addDependency(compatDep);
parser.state.harmonyModule = true;
parser.scope.isStrict = true;
module.buildMeta.exportsType = "namespace";
module.buildInfo.strict = true;
module.buildInfo.exportsArgument = "__webpack_exports__";
2018-02-25 09:00:20 +08:00
if (isStrictHarmony) {
module.buildMeta.strictHarmonyModule = true;
module.buildInfo.moduleArgument = "__webpack_module__";
}
}
});
2017-11-08 18:32:05 +08:00
const skipInHarmony = () => {
const module = parser.state.module;
if (module && module.buildMeta && module.buildMeta.exportsType) {
2017-11-08 18:32:05 +08:00
return true;
}
2017-11-08 18:32:05 +08:00
};
const nullInHarmony = () => {
const module = parser.state.module;
if (module && module.buildMeta && module.buildMeta.exportsType) {
2017-11-08 18:32:05 +08:00
return null;
}
2017-11-08 18:32:05 +08:00
};
2017-11-15 16:28:45 +08:00
const nonHarmonyIdentifiers = ["define", "exports"];
for (const identifier of nonHarmonyIdentifiers) {
2018-02-25 09:00:20 +08:00
parser.hooks.evaluateTypeof
.for(identifier)
2018-02-25 09:00:20 +08:00
.tap("HarmonyDetectionParserPlugin", nullInHarmony);
parser.hooks.typeof
.for(identifier)
2018-02-25 09:00:20 +08:00
.tap("HarmonyDetectionParserPlugin", skipInHarmony);
parser.hooks.evaluate
.for(identifier)
2018-02-25 09:00:20 +08:00
.tap("HarmonyDetectionParserPlugin", nullInHarmony);
parser.hooks.expression
.for(identifier)
2018-02-25 09:00:20 +08:00
.tap("HarmonyDetectionParserPlugin", skipInHarmony);
parser.hooks.call
.for(identifier)
2018-02-25 09:00:20 +08:00
.tap("HarmonyDetectionParserPlugin", skipInHarmony);
2018-01-22 20:52:43 +08:00
}
}
};