Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack - Using Script Loader in webpack.config.json

I am just starting to dip my toes into the world of webpack. I am using the awesome Vue.js with vueify, so therefore my modules are ES6.

One difficulty I am having is loading some 3rd party jQuery plugins. I am using the ProvidePlugin to load jQuery - which works fine.

plugins: [
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery"
        })
    ]

I then have a directory called plugins containing misc jQuery plugins. My understanding is the script loader just loads these into the bundled file as strings, and they are eval-ed when the bundle loads. These scripts can then be used as if they were loaded in a regular script tag (i.e., no import needed).

But I just cant get any of the plugins to work. Below is my loaders array. What I am doing wrong (or not doing)?

loaders: [

        // process *.vue files using vue-loader
        {
            test: /\.vue$/,
            loader: 'vue'
        },
        // process *.js files using babel-loader
        // the exclude pattern is important so that we don't
        // apply babel transform to all the dependencies!
        {
            test: /\.js$/,
            loader: 'babel',
            exclude: /node_modules/
        },
        {
            test: /plugins\.js$/,
            loader: 'script-loader' #tried script too
        }

    ]
like image 805
user163757 Avatar asked May 21 '16 14:05

user163757


1 Answers

I can sympathize with the difficulty of getting jQuery plugins to work with webpack. While I don't have a solution to this specific configuration, I have found it useful to use a cdn to keep development rolling along until further troubleshooting can be done. Below is an example.

In your .html template file:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

In index.js or whatever your main entry point is:

import $ from 'jquery'

In your webpack config:

externals: {
    jquery: 'jQuery'
}

Since this approach involves direct use of script tags it may work more reliably, while temporarily sacrificing opportunities for optimization and bundling.

like image 174
bdellaterra Avatar answered Oct 15 '22 09:10

bdellaterra