【问题标题】:Importing jQuery plugins in webpack在 webpack 中导入 jQuery 插件
【发布时间】:2017-06-27 02:14:26
【问题描述】:

我搜索并发现了很多关于 Angular 或 React 的文章。我的项目不包括这些。

我只是尝试使用 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

当我查找此内容时,我发现“未定义”指的是文档。文档没有定义怎么办?为什么这个导入不起作用。

使用方法:

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]      ]

【问题讨论】:

  • 是在浏览器还是节点服务器上运行?
  • webpack 开发服务器

标签: javascript jquery webpack es6-module-loader


【解决方案1】:

您使用的库可能希望将 this 设置为 window,但事实并非如此。我在modernizr 上遇到了同样的问题,并用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

【讨论】:

  • 那么 require.resolve('modernizr') 是否指向插件的路径?
  • 是JS文件的名称/路径:node_modules/modernizr/modernizr.js。详情见这里:webpack.js.org/configuration/resolve/#resolve
  • 我的模块不在 node_modules 中......这是相对于什么路径?配置文件还是相对于node_moduels?似乎都不起作用
  • 抱歉,看到您的问题中的更新错误,“规则”需要在“模块”对象中。我更新了我的答案。
  • 通读了几遍这篇文章以了解它,这是正确的答案。这种方法的变体将解决这个问题。
猜你喜欢
  • 2020-11-19
  • 2019-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-12
  • 1970-01-01
  • 2020-12-17
  • 1970-01-01
相关资源
最近更新 更多