在 webpack 中导入 jQuery 个插件

Importing jQuery plugins in webpack

我搜索并发现许多文章最谈论 angular 或反应。我的项目不包括这些。

我只是想使用 webpack 将旧的 jquery 模块导入 js 文件。

我有 jquery 使用此方法包括:

plugins: [
    new webpack.ProvidePlugin({
        $: "jquery",
        jQuery: "jquery"
    })
]

这行得通。我可以访问我需要的文件中的 jquery。

然而,当我尝试导入脚本时:

import coverflow from '../vendor/coverflow/dist/coverflow';

来源: https://github.com/coverflowjs/coverflow

我收到浏览器错误

Cannot read property 'createElement' of undefined

当我查找它时,我发现 'undefined' 指的是文档。文件怎么没有定义?为什么这个导入不起作用。

使用方法:

rules: [
    {
        test: require.resolve('./js/vendor/coverflow/dist/coverflow.js'),
        use: "imports-loader?this=>window"
    }
],

我收到这个错误:

[0] Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
[0]  - configuration has an unknown property 'rules'. These properties are valid:
[0]    object { amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry, externals?, loader?, module?, name?, node
?, output?, performance?, plugins?, profile?, recordsInputPath?, recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, stats?,
 target?, watch?, watchOptions? }
[0]    For typos: please correct them.
[0]    For loader options: webpack 2 no longer allows custom properties in configuration.
[0]      Loaders should be updated to allow passing options via loader options in module.rules.
[0]      Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:
[0]      plugins: [
[0]        new webpack.LoaderOptionsPlugin({
[0]          // test: /\.xxx$/, // may apply this only for some modules
[0]          options: {
[0]            rules: ...
[0]          }
[0]        })
[0]      ]

您正在使用的库可能希望将 this 设置为 window,但事实并非如此。我对 modernizr and solved it with the imports-loader 也有同样的问题,如下所示:

module: {
  rules: [
  {
    test: require.resolve('modernizr'),
    use: [
      'expose-loader?Modernizr',
      'imports-loader?this=>window!exports-loader?window.Modernizr'
    ]
  }
}

重要的部分是 this=>window。你可以 read more details about how I solved it here.