webpack/lib/node/NodeSourcePlugin.js

84 lines
2.1 KiB
JavaScript
Raw Normal View History

2013-01-31 01:49:25 +08:00
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
2018-07-30 23:08:51 +08:00
2017-05-07 02:41:26 +08:00
"use strict";
2018-07-03 16:24:29 +08:00
2018-07-25 02:05:29 +08:00
const { getModulePath } = require("../JavascriptParserHelpers");
const ProvidedDependency = require("../dependencies/ProvidedDependency");
2013-01-31 01:49:25 +08:00
/** @typedef {import("../../declarations/WebpackOptions").NodeOptions} NodeOptions */
2018-11-09 05:59:19 +08:00
/** @typedef {import("../Compiler")} Compiler */
2017-05-07 02:41:26 +08:00
module.exports = class NodeSourcePlugin {
/**
* @param {NodeOptions | false} options plugin options
*/
2017-05-07 02:41:26 +08:00
constructor(options) {
this.options = options;
2014-03-19 05:34:35 +08:00
}
2018-11-09 05:59:19 +08:00
/**
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
2017-05-07 02:41:26 +08:00
apply(compiler) {
const options = this.options;
if (options === false) {
2018-02-25 09:00:20 +08:00
// allow single kill switch to turn off this plugin
return;
}
2018-02-25 09:00:20 +08:00
compiler.hooks.compilation.tap(
"NodeSourcePlugin",
(compilation, { normalModuleFactory }) => {
2018-07-25 02:05:29 +08:00
compilation.dependencyFactories.set(
ProvidedDependency,
normalModuleFactory
);
compilation.dependencyTemplates.set(
ProvidedDependency,
new ProvidedDependency.Template()
);
2018-02-25 09:00:20 +08:00
const handler = (parser, parserOptions) => {
if (parserOptions.node === false) return;
2018-02-25 09:00:20 +08:00
let localOptions = options;
if (parserOptions.node) {
2018-02-25 09:00:20 +08:00
localOptions = Object.assign({}, localOptions, parserOptions.node);
}
2018-02-25 09:00:20 +08:00
if (localOptions.global) {
parser.hooks.expression
.for("global")
2018-07-25 02:05:29 +08:00
.tap("NodeSourcePlugin", expr => {
2018-07-25 03:57:48 +08:00
const dep = new ProvidedDependency(
getModulePath(
parser.state.module.context,
require.resolve("../../buildin/global")
),
"global",
null,
expr.range
2018-02-25 09:00:20 +08:00
);
2018-07-25 03:57:48 +08:00
dep.loc = expr.loc;
2018-07-27 21:57:03 +08:00
parser.state.module.addDependency(dep);
2018-02-25 09:00:20 +08:00
});
}
};
2018-02-25 09:00:20 +08:00
normalModuleFactory.hooks.parser
.for("javascript/auto")
.tap("NodeSourcePlugin", handler);
normalModuleFactory.hooks.parser
.for("javascript/dynamic")
.tap("NodeSourcePlugin", handler);
normalModuleFactory.hooks.parser
.for("javascript/esm")
.tap("NodeSourcePlugin", handler);
}
);
2017-05-07 02:41:26 +08:00
}
};