I have a very simple Webpack 4 example where I am trying to access the jQuery object in my entry file in order to manipulate the DOM. I have pared it down to what I think is the bare minimum having researched extensively.
I expect the example to set the background color of the body
to cyan upon page load. Can't seem to get it to do anything. Looks like the $
variable exposed in the entry file is not the same $
variable in the browser.
UPDATE - PROBLEM SOLVED : I was misusing jQuery
below.
Original (defective) entry file ( src/app.js
):
import 'jquery';
$(() => {
$('body').bgColor = 'cyan';
});
Corrected entry file:
import 'jquery';
$(() => {
$('body').css('background-color', 'cyan');
});
I use the ProvidePlugin
as documented here . Here is my simple webpack.config.js
file:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require("webpack");
module.exports = {
entry: {
app: './src/app.js',
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
}),
new HtmlWebpackPlugin()
],
devtool: 'inline-source-map'
}
Webpack compiles just fine and the page opens (using webpack-dev-server
), but the background color does not change to cyan as expected. When I log the value of $('body')
in the app.js
file, I get undefined
.
Here is the package.json
file:
{
"name": "foo",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"start": "webpack-dev-server --inline --open"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.16.5",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.5"
},
"dependencies": {
"jquery": "^3.3.1"
}
}
Feels like I have a fundamental lack of understanding of how this is supposed to work. Thanks. Your help is greatly appreciated.
Apologies. My mistake on misuse of jQuery. Thanks to @charlietfl for pointing out my mistake in the comments. I used. $('body').bgColor = "cyan"
instead of $('body').css('background-color', 'cyan')
. Everything else is properly configured. So if you need a simple example, here it is.
I will edit the question and point out my mistake.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.