search

Home  >  Q&A  >  body text

Steps to install jQuery in Nuxt.js

Although I tried adding jQuery to my project, I encountered an error saying it was undefined.

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' }, <-- 给我报错
    { 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 this happens, obviously I have declared jQuery before bootstrap-select.

P粉755863750P粉755863750420 days ago712

reply all(1)I'll reply

  • P粉277824378

    P粉2778243782023-11-07 10:37:21

    I do not recommend adding jQuery to Nuxt projects.


    But if you really want to add it, you can follow the steps below:

    • Use yarn add jqueryInstall it
    • Add the following to your nuxt.config.js file
    import webpack from 'webpack'
    
    export default {
      // ...
      build: {
        plugins: [
          new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery'
          })
        ]
      },
    }
    
    • Make sure your .eslintrc.js file has the following content
    module.exports = {
      // ...
      env: {
        // ...
        commonjs: true,
        jquery: true
      },
    }
    

    Then, you can use it like this in method or similar

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

    reply
    0
  • Cancelreply