如果没有 jQuery,Webpack 无法加载 backbone

Webpack fails to load backbone without jQuery

我有以下 webpack 配置:

module.exports = {
    entry: "./league/index.ts",
    output: {
        path: "./",
        filename: "bundle.js"
    },
    resolve: {
        // Add `.ts` and `.tsx` as a resolvable extension.
        extensions: ["", ".ts", ".js"]
    },
    module: {
        loaders: [
            // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
            { test: /\.ts?$/, loader: "ts-loader" }
        ]
    }
};

当我 运行 webpack 时,我得到这个错误(实际项目路径替换为 PROJECT_PATH 以保护隐私):

ERROR in ./~/backbone/backbone.js
Module not found: Error: Cannot resolve module 'jquery' in PROJECT_PATH\node_modules\backbone
 @ ./~/backbone/backbone.js 17:4-21:6

原因是 backbone.js 中的这段代码:

  // Set up Backbone appropriately for the environment. Start with AMD.
  if (typeof define === 'function' && define.amd) {
    define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
      // Export global even in AMD case in case this script is loaded with
      // others that may still expect a global Backbone.
      root.Backbone = factory(root, exports, _, $);
    });

  // Next for Node.js or CommonJS. jQuery may not be needed as a module.
  } else if (typeof exports !== 'undefined') {
    var _ = require('underscore'), $;
    try { $ = require('jquery'); } catch (e) {}
    factory(root, exports, _, $);

  // Finally, as a browser global.
  }

jQuery 不是我需要的依赖项,但是 webpack 正在解释 require 调用,因为我需要它。

Backbone依赖于jQuery,如果像zepto一样使用其他类似jQuery的模块,需要给它起别名jquery .

来自Backbone wiki

Using WebPack, the resolve.alias configuration option can be used:

{
    context: __dirname + "/app",
    entry: "./entry",
    output: {
        path: __dirname + "/dist",
        filename: "bundle.js"
    }
    resolve: {
        alias: {
            "jquery": "zepto"
        }
    }
}