vue-cli搭建的vue項目中使用到jquery插件,需要引入jquery,
在無任何配置的情況下,直接在組件中import引入,在mounted時候打印$ 會顯示undefined報錯問題,
感覺直接引入不應該報這種錯誤,之前這么使用都是沒問題的,網上查閱說有可能是如果項目使用了 eslint語法檢驗,此時 會提示 找不到 $或者jquery的錯誤。
錯誤如下:
http://eslint.org/docs/rules/no-undef '$' is not defined
http://eslint.org/docs/rules/no-undef 'jQuery' is not defined
我的報錯顯然跟eslint無關,但還是進行了相關配置,配置如下:
在eslintrc.js文件的module.exports中,為env添加一個鍵值對 jquery: true 就可以了,也就是:
env: {
// 原有
browser: true,
// 添加
jquery: true
}
由於不是eslint的問題,我這邊配置完之后當然還是報錯$ undefined,
然后就考慮是jquery引入方式的問題,換了一種方式引入,
1. 在package.json中安裝 jquery文件到dependencies中
2.在build文件夾下找到webpack.base.conf.js文件進行設置,使用webpack引入jquery,
(1)在頭部引入webpack var webpack = require(‘webpack’)
(2)在module對jquery進行全局配置,在module.exports中加入以下代碼
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
jquery: "jquery",
"window.jQuery": "jquery"
})
],
(3)在main.js中引入 jquery,
import $ from 'jquery'
(4)配置完畢,重新運行項目,OK