需要一个带Webpack的jQuery-Plugin

时间:2017-03-09 15:31:39

标签: jquery-plugins webpack webpack-2

我想使用Webpack从所有需要的Javascript文件中创建一个scripts.js文件。

在我的main.js中,我需要三个模块:

require('jquery');
require('readmore');
require('foundation');

我的webpack.config.js就是这样:

var path = require('path');

module.exports = {
    entry: ["./js/main.js"],
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: "scripts.js"
    },
    resolve: {
        modulesDirectories: ["bower_components", "node_modules"],
        alias: {
            jquery: '../bower_components/jquery/dist/jquery.js',
            readmore: '../node_modules/readmore-js/readmore.js',
            foundation: '../bower_components/foundation-sites/dist/js/foundation.js'
        }
    }
}

我的问题:由于readmore-js是一个jQuery-Plugin,它本身需要jQuery。 运行Webpack后出现此错误:

ERROR in ./~/readmore-js/readmore.js
Module not found: Error: Can't resolve 'jquery' in '/Users/myName/www/myProject/node_modules/readmore-js'
 @ ./~/readmore-js/readmore.js 17:4-31
 @ ./js/main.js
 @ multi main

根据我的理解,问题是readmore还想在目录“nodes_modules”中加载模块jQuery。我的第一种方法是通过将moduleDirectories添加到配置文件来解决此问题,但它仍然无效。 即使在这种情况下,插件也不应该再次加载jQuery。

你知道如何全局加载jQuery然后“告诉”所有需要jQuery的模块“看看,它就在那里!”

虽然它可能会有所帮助,但以下内容将从插件的readmore.js

中复制出来
(function(factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD
    define(['jquery'], factory);
  } else if (typeof exports === 'object') {
    // CommonJS
    module.exports = factory(require('jquery'));
  } else {
    // Browser globals
    factory(jQuery);
  }
}

1 个答案:

答案 0 :(得分:0)

您可以使用webpack.ProvidePlugin

main.js删除需要jquery:

require('readmore');
require('foundation');

webpack.config.js

中配置webpack.ProvidePlugin
var path = require('path');

module.exports = {
    entry: ["./js/main.js"],
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: "scripts.js"
    },
    resolve: {
        modulesDirectories: ["bower_components", "node_modules"],
        alias: {
            readmore: '../node_modules/readmore-js/readmore.js',
            foundation: '../bower_components/foundation-sites/dist/js/foundation.js'
        }
    },
    plugins: [
      new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery'
      }),
    ]
}