I have next html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" href="css/main.css" />
<script src="js/main.js"></script>
</head>
<body>
<button type="button" class="btn btn-outline-warning"
onclick='debugger;lazy_load( $("#load") )'
>Primary</button>
<div id="load">
<div data-lazy-load="ajax/data-ajax.json">Loading...</div>
<div data-lazy-load="ajax/data-ajax.html">Loading...</div>
</div>
</body>
</html>
import { ajax_query } from "../common/ajax";
export function lazy_load( container ) {
container ||= $('#load');
...
}
webpack.config.js
has:
plugins: config.scripts.isUseJquery
? [
new webpack.ProvidePlugin({
jQuery: "jquery",
jquery: "jquery",
$: "jquery",
"window.jQuery": "jquery",
"window.jquery": "jquery",
"window.$": "jquery",
}),
]
: [],
};
When I open this page I get Uncaught ReferenceError: $ is not defined
near this code lazy_load( $("#load") )
.
When I remove parameter $("#load")
then same code inside lazy_load
works fine.
Even when script execution stop at debugger
, I can run $("#load")
at console without any error!
Why onclick='lazy_load( $("#load") )'
does not work?
When I replace onclick: onclick='lazy_load()'
CodePudding user response:
When coding with modules, you should also import jQuery explicitly:
import $ from "jquery";
import { ajax_query } from "../common/ajax";
export function lazy_load( container ) {
container ||= $('#load');
...
}
Otherwise see more possible solutions here:
How to import jQuery in webpack
CodePudding user response:
To make $
global I must to expose it.
So I install expose-loader
and adjust my webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("jquery"),
loader: 'expose-loader',
options: { exposes: [ '$', 'jQuery' ] },
},
],
}
}
Notice: for webpack 5 there is different config format, so I install expose-loader
version 1.0.3