Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

javascript - How to install jQuery into Nuxt.js?

I'm trying to add jQuery in my project although i get an error that it is not defined

  plugins: [
    { src: '~/plugins/js/svgSprite.js', mode: 'client' },
    { src: '~/plugins/vendor/jquery/jquery.min.js', mode: 'client' },
    { src: '~/plugins/vendor/bootstrap/js/bootstrap.bundle.min.js', mode: 'client' },
    { src: '~/plugins/vendor/bootstrap-select/js/bootstrap-select.min.js', mode: 'client' }, <-- gives me error
    { src: '~/plugins/vendor/magnific-popup/jquery.magnific-popup.min.js', mode: 'client' },
    { src: '~/plugins/vendor/smooth-scroll/smooth-scroll.polyfills.min.js', mode: 'client' },
    { src: '~/plugins/vendor/object-fit-images/ofi.min.js', mode: 'client' },
    { src: '~/plugins/js/theme.js', mode: 'client' }
  ],

Why is this happening, I'm obviously declaring jQuery before bootstrap-select.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I do not recommend adding jQuery to a Nuxt project.


But if you really want to, you can follow those steps:

  • install it with yarn add jquery
  • add those to your nuxt.config.js file
import webpack from 'webpack'

export default {
  // ...
  build: {
    plugins: [
      new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery'
      })
    ]
  },
}
  • be sure that you do have the following in your .eslintrc.js file
module.exports = {
  // ...
  env: {
    // ...
    commonjs: true,
    jquery: true
  },
}

Then, you can use it like this in a method or alike

$("h2").addClass("tasty-class")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...