Using jQuery with Webpack

I am transitioning from RequireJS to Webpack and am having problems using jQuery for my modules.

I know there are some answers about this, and I went through them, but I can't get it to work. This is: Managing the dependency of the jQuery plugin in the web package - this is the one I read.

My webpack.config.js looks like this:

var webpack = require("webpack");
var bower_dir = __dirname + '/bower_components';

var config = {
    addVendor: function(name, path) {
        this.resolve.alias[name] = path;
        //this.module.noParse.push(new RegExp(path));
    },
    entry: {
        app: ['./app/js/main.js'],
        vendors: ['jquery', 'bootstrap']
    },
    resolve: { alias: {} },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.js'),
        new webpack.ProvidePlugin({
            $: "jquery",
            jQuery: "jquery",
            "window.jquery": "jquery"
        })
    ],
    output: {
        path: './build',
        filename: 'bundle.js'
    },
    module: {
        noParse: [bower_dir + '/bootstrap/dist/js/bootstrap.min.js'],
        loaders: []
    }
};

config.addVendor('jquery', bower_dir + '/jquery/jquery.js');
config.addVendor('bootstrap', bower_dir + '/bootstrap/dist/js/bootstrap.min.js');

module.exports = config;

I use ProvidePlugin to require jQuery for every module that uses it. In addition, I put the file in the library suppliers vendors.js my modules main.js .

My main.js file has several lines of code to check if $ jQuery is allowed:

$(".search-toggle").on("click", function(e) {
    e.preventDefault();
    $(".search-container").toggle();
});

index.html :

<script src="<s:url  value="/resources/build/vendors.js"/>"></script>
<script src="<s:url  value="/resources/build/bundle.js"/>"></script>

, Uncaught TypeError: $ , $ .

, , .

!

+4
1

webpack.ProvidePlugin https://github.com/webpack/expose-loader:
loaders: [{ test: require.resolve('jquery'), loader: 'expose?$!expose?jQuery', }]

+1

Source: https://habr.com/ru/post/1608658/


All Articles