1

I'm trying to get $ and jQuery to work in the DOM after loading them with webpack. I will need jQuery for some extra dom manipulations that I will do with alongside video.js.

I've read through the webpack docs and this but although I can get jquery to work inside the bundle file with no problems, I can't seem to get it working outside of it.

My files in their current state:

webpack.config.js

var path = require('path');
var webpack = require('webpack');

module.exports = {
    entry: './js/index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    },
    plugins : [
        new webpack.ProvidePlugin({$: 'jquery',jQuery: 'jquery'})
    ],
};

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Webpack test</title>
</head>
<body>
<div id="playerContainer"> </div>
<script type="text/javascript" src="./dist/bundle.js"></script>
</body>
</html>

index.js

jQuery("body").css("background","red");
$("body").css("background","blue");

package.json

{
  "name": "webpack-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "jquery": "^3.2.1"
  },
  "devDependencies": {
    "webpack-dev-server": "^2.4.5",
    "webpack": "^2.6.1"
  },
  "scripts": {
    "start": "webpack -w",
    "server": "webpack-dev-server"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Is it possible to get jQuery (and maybe other libraries) to work in the browser?

wadge
  • 428
  • 5
  • 18
  • 3
    In your `index.js` you will have to expose jquery to `window` so other 3rd party libraries have access to it. All you need to do is this one line: `window['jQuery'] = window['$'] = require('jquery');` – Pavel Denisjuk Jun 11 '17 at 16:55
  • I wish I could upvote a response a million times. This is the answer for my similar question here: https://stackoverflow.com/questions/46122512/how-to-use-jquery-from-views-on-rails-5-1-3-webpacker **Thanks!** – Will Raben Sep 08 '17 at 18:36

0 Answers0