问题描述
前段时间做个H5单页想着太简单就没上Vue这样的框架直接jq一把梭,然后在项目刚搭建环境时就出现了 $ is not defined的问题,经过一番检查,确认jq已经打包进项目且运行在业务代码之前,但是$就是没有挂载到window上,然后经过一番苦苦的寻找最后问题定位在了webpack上。
原因分析
本人使用的是webpack最新版本5.3.2,webpack-cli为4.2.0,因为我想要把jq单独打包成一个文件因此没有选择webpack.ProvidePlugin注入$的方法,而是把jq当成一个entry打包然后在HtmlWebpackPlugin形成模板时引入到页面中。咋一看好像没什么问题,页面也有引入打包好的jq,但是跑起来就是 $ is not defined,然后我就尝试着在jq里面打断点,果然jq里面的逻辑没有走到将$挂载到window上的逻辑,jq里有段判断环境的代码,如下:
if (typeof module === "object" && typeof module.exports === "object") {
// For CommonJS and CommonJS-like environments where a proper `window`
// is present, execute the factory and get jQuery.
// For environments that do not have a `window` with a `document`
// (such as Node.js), expose a factory as module.exports.
// This accentuates the need for the creation of a real `window`.
// e.g. var jQuery = require("jquery")(window);
// See ticket #14549 for more info.
module.exports = global.document ?
factory(global, true) :
function (w) {
if (!w.document) {
throw new Error("jQuery requires a window with a document");
}
return factory(w);