2

I created a vuejs2 project with latest vue-cli and tried to import jQuery into the project by using expose-loader, I think I followed the instruction in the official readme but got no luck.

What I've done:

  • install jquery and expose-loader via npm
  • insert the lines below in build/webpack.base.conf.js

But when I typed console.log(window.jQuery) in Chrome devtool's console, I still got undefined.

// ...
module: {
  rules: [
    // added for supporting jquery
    {
      test: require.resolve('jquery'),
      use: [{
        loader: 'expose-loader',
        options: 'jQuery'
      },{
        loader: 'expose-loader',
        options: '$'
      }]
    },
// ...

What did I miss?

2 Answers 2

2

You can try without the expose-loader using the ProviderPlugin

  1. npm install jquery --save
  2. Now in your build/webpack.base.conf.js

    module.exports = { 
        plugins: [ 
            new webpack.ProvidePlugin({ 
                $: 'jquery', 
                jQuery: 'jquery',
                'window.jQuery': 'jquery'
            }) 
        ]
        //..
    } 
    
Sign up to request clarification or add additional context in comments.

1 Comment

Hi! Thanks for your advise, but I think expose-loader may be a better choice for me after reading this: stackoverflow.com/questions/29080148/…
0

To do this in my application, I make this a bit more explicit in my entry point file directly in the import statement:

import 'expose-loader?$!expose-loader?jQuery!jquery';

This exposes jquery to the $ and jQuery variables via the expose-loader plugin.

6 Comments

Yep, require("expose-loader?$!jquery"); can also do the trick, but I'm wondering why it doesn't work when setting it in webpack's config file.
Do you have an alias for jquery setup? I found that the config that you are trying to use didn't work with an alias to a minified version of jquery. If I removed the alias though, then things worked fine. The inlined version I mentioned above works just fine when I use the an alias to the minified version though. Why this happens, not exactly sure.
Hi, thanks for your comment. I'm sorry but I'm not sure what "alias" are you pointing at. If you mean the alias in the resolve property, here's my resolve property, which was defined by vue-cli and hasn't been modified by myself. resolve: {extensions: ['.js', '.vue', '.json'], alias: {'vue$': 'vue/dist/vue.esm.js', '@': resolve('src') } }
btw, I used vue-cli's webpack template to generate my project.
Yes, the resolve.alias section is what I'm referring to. I'm not sure what the '@' entry is for... maybe try removing it as a test to see if jquery works then. Sorry I don't have anything more official.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.