问题描述
我正在 VueJS 中构建 Web 应用程序,但遇到问题.我想使用 jQuery 扩展(具体来说是cropit),但我不知道如何以正确的方式实例化/要求/导入它而不会出错.
I'm building a web application inside VueJS but I encounter a problem. I want to use a jQuery extension (cropit to be specific) but I don't know how to instantiate/require/import it the right way without getting errors.
我正在为我的应用程序使用官方 CLI 工具和 webpack 模板.
I'm using de official CLI tool and de webpack template for my App.
我在 main.js 文件中包含了这样的 jQuery:
I included jQuery like this in my main.js file:
import jQuery from 'jQuery'
window.jQuery = jQuery
现在我正在构建一个图像编辑器组件,我想像这样实例化 crept:
Now I'm building an image editor component where I want to instantiate crept like this:
export default {
ready () {
$(document).ready(function ($) {
$('#image-cropper-wrapper-element').cropit({ /* options */ })
})
},
}
但我不断收到错误...现在我的问题是如何通过 NPM/Webpack/Vue 正确实例化 jQuery 和插件?
But I keep getting errors...Now my question is how to properly instantiate jQuery and plugins via NPM/Webpack/Vue?
提前致谢!
推荐答案
选项#1:使用ProvidePlugin
将 ProvidePlugin 添加到两个 build/webpack.dev.conf.js
和 build/webpack.prod.conf.js
以便 jQuery 对您的所有模块全局可用:
Add the ProvidePlugin to the plugins array in both build/webpack.dev.conf.js
and build/webpack.prod.conf.js
so that jQuery becomes globally available to all your modules:
plugins: [
// ...
new webpack.ProvidePlugin({
$: 'jquery',
jquery: 'jquery',
'window.jQuery': 'jquery',
jQuery: 'jquery'
})
]
选项 #2:为 webpack 使用 Expose Loader 模块
正如@TremendusApps 在他的回答中所建议的,添加 Expose Loader 包:>
As @TremendusApps suggests in his answer, add the Expose Loader package:
npm install expose-loader --save-dev
像这样在你的入口点 main.js
中使用:
Use in your entry point main.js
like this:
import 'expose?$!expose?jQuery!jquery'
// ...
这篇关于如何在 Vue 中使用 jQuery 插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!