繁体   English   中英

如何在vuejs webpack cli项目中包含jquery?

[英]How to include jquery in a vuejs webpack cli project?

你好我曾经在vuejs cli生成一个项目( https://github.com/vuejs/vue-cli )。 cli使用webpack,我在vue文件中使用jquery时遇到了麻烦。 我总是得到一个。

http://eslint.org/docs/rules/no-undef  '$' is not defined

我已经尝试编辑我的webpack.dev.config以包含提供插件块,如下所示:

var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')

// add hot-reload related code to entry chunks
Object.keys(baseWebpackConfig.entry).forEach(function (name) {
  baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
})

module.exports = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap })
  },
  // cheap-module-eval-source-map is faster for development
  devtool: '#cheap-module-eval-source-map',
  plugins: [
    new webpack.DefinePlugin({
      'process.env': config.dev.env
    }),
    // https://github.com/glenjamin/webpack-hot-middleware#installation--usage
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    // https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      inject: true
    }),
    new FriendlyErrorsPlugin(),
    new webpack.ProvidePlugin({
      $ : "jquery",
      jQuery : "jquery"
    })
  ]
})

但是当试图使用jquery时,我会一次又一次地遇到同样的问题。 我不反对使用cdn这个我真的不能让这个想法包括jquery无论我尝试什么。

如果vue文件是有用的,我会在脚本块中尝试console.log $

<script>
export default {
  name: 'how_can_we_help_you',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  }
}
console.log($)
</script>

请帮助我非常卡住,并一直试图修复这个非常诡计。 提前致谢。

进入main.js并做

window.$ = window.jQuery = require('jquery')

要么

Vue.use({
    install: function(Vue, options){
        Vue.prototype.$jQuery = require('jquery'); // you'll have this.$jQuery anywhere in your vue project
    }
})

经过两天的搜索。 它的eslintrc.js

将此添加到以下内容,它将修复提供插件。

env: {
  browser: true,
  jquery: true
},

对于那些不使用webpack的人来说,另一种方法是使用expose-loader:

yarn add expose-loader

和你的main.js

import "expose-loader?$!jquery";

我找到了解决方案。 我将更改放在webpack.dev.conf.js而不是webpack.dev.config和eslintrc.json而不是eslintrc.js。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM