将JQuery插件与Webpack结合使用

时间:2020-01-02 17:06:44

标签: jquery webpack galleria

我正在尝试将插件Galleria与Webpack一起使用。没有Webpack的Galleria可以用作:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
<script src="galleria/galleria-1.4.min.js"></script>

<script>
  (function() {
    Galleria.loadTheme('https://cdnjs.cloudflare.com/ajax/libs/galleria/1.5.7/themes/classic/galleria.classic.min.js');
    Galleria.run('.galleria');
  }());
</script>

也可以手动加载主题,而不是使用方法loadTheme

<link rel=”stylesheet” type=”text/css” href=”https://cdnjs.cloudflare.com/ajax/libs/galleria/1.5.7/themes/fullscreen/galleria.classic.min.css” />

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>   
<script src=”https://cdnjs.cloudflare.com/ajax/libs/galleria/1.5.7/galleria.min.js”></script>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/galleria/1.5.7/themes/classic/galleria.classic.min.js”></script>

<script>
  (function() {
    Galleria.run('.galleria');
  }());
</script>

使用WebPack,我将以下代码添加到Index.js:

import galleria from 'galleria';

import '../../node_modules/galleria/dist/themes/classic/galleria.classic.css';
import '../../node_modules/galleria/dist/themes/classic/galleria.classic.js';

window.Galleria = galleria; 

(function() {
  Galleria.run('.galleria');
}());

运行它时出现错误:

No theme CSS loaded.

Init failed: Galleria could not find the element "undefined".

有人知道如何在Webpack中使用Galleria吗?

1 个答案:

答案 0 :(得分:4)

为您创建了一个带有Webpack和Galleria的简单repo
步骤是:

  1. 按照记录here使用shimming
            {
                test: /galleria.js$/,
                loader: "imports-loader?this=>window"
            },
  1. jquerygalleria添加为项目的依赖项: npm i -S jquery galleria
  2. 使用loadThemerun Galleria方法:
import * as $ from 'jquery';
import galleria from 'galleria';

window.Galleria = galleria;
window.jQuery = $;

Galleria.loadTheme('node_modules/galleria/dist/themes/classic/galleria.classic.js');
Galleria.run('.galleria');

要查看项目是否正常运行,请运行npm run start

UPD:
要复制缩小的主题文件,可以使用CopyWebpackPlugin

  1. npm i -D copy-webpack-plugin
  2. 将其添加到webpack插件中:
plugins: [
        new CopyWebpackPlugin([
            { from: 'node_modules/galleria/dist/themes/classic/galleria.classic.min.js', to: 'assets/galleria.classic.js' },
            { from: 'node_modules/galleria/dist/themes/classic/galleria.classic.min.css', to: 'assets/galleria.classic.css' },
        ])
]
  1. 更改loadTheme通话中的路径:Galleria.loadTheme('assets/galleria.classic.js');

UPD2:
使用webpack imports更新了仓库。 请查看此PR或此branch的不同之处。 主要变化是:

  1. 我们仍然需要galleria.classic.css文件与copy-webpack-plugin一起使用并作为<link rel="stylesheet" type="text/css" href="assets/galleria.classic.css">加载,因为我在源代码中发现css只能通过{{1}加载}或link标签或动态(script调用),否则将打印loadThemesource
    1. 但是我们的JavaScript代码变得非常简单。我也用No theme css loaded删除了webpack规则,并以内联样式使用了它。
imports-loader