I want to switch from gulp to webpack but I struggle with jQuery.
Issue: In Dev-Console on Chrome I alway get the following issue:
external var "jQuery":1 Uncaught ReferenceError: jQuery is not defined
at Object.jquery (external var "jQuery":1)
at __webpack_require__ (bootstrap:19)
at jquery-ui.js:10
at Object../source/js-ogs/vendor/jquery-plugins/jquery-ui.js (jquery-ui.js:16)
at __webpack_require__ (bootstrap:19)
at ogs-vendor.ts:7
at ogs-vendor.ts:24
at ogs-vendor.ts:24
If I click on the file it shows me the following line causing the issue:
module.exports = jQuery;
Project-Structure: I got two files:
- project-vendor.js (linked in head)
- project.js (linked in body)
project-vendor.js should bundle the following files:
import '../../js/vendor/jquery-3.3.0'
import '../../js/vendor/jquery-plugins/jquery-ui'
import '../../js/vendor/jquery-plugins/isInViewport'
import '../../js/vendor/jquery-plugins/jquery.selectBox'
import '../../js/vendor/jquery-plugins/jquery.sumoselect'
import '../../vendor/polyfills/after-polyfill'
import '../../vendor/polyfills/polyfill-array-includes'
import '../../js/vendor/element-closest-polyfill'
import '../../js/vendor/bootstrap/bootstrap'
Webpack-Config:
{
output: {
path: path.resolve(getPublicPath('path')),
filename: '[name].js',
clean: true,
},
externals: [
{
jquery: 'jQuery',
datatables: 'datatables'
}
],
name: 'NAME',
entry: {
'js/project.min': './source/typescript/layouts/project.ts',
'js/project-vendor.min': './source/vendor/layouts/project-vendor.ts',
},
devtool: 'inline-source-map',
mode: 'development',
resolve: {
extensions: ['.ts', '.js', '.json']
},
plugins: [
new MiniCssExtractPlugin({ filename: 'css/project.min.css' }),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
})
],
module: {
rules: [
{ test: /\.(sa|sc|c)ss$/, use: [{ loader: MiniCssExtractPlugin.loader }, 'css-loader','sass-loader',] },
{ test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/ },
{ test:require.resolve('jquery'), use: [{
loader: "imports-loader",
options: {
imports: {
moduleName: "jquery",
name: "$",
},
additionalCode: "var define = false; var exports = undefined; /* Disable AMD for misbehaving libraries */",
}
}]}
]
}
},
What I tried: I found this: Managing jQuery plugin dependency in webpack (Accepted Answer) and it looks like step 3 could fix my problem. But this question is old and the imports-loader changed. (https://webpack.js.org/loaders/imports-loader/) And I have no idea how to use it correctly. I tried the jquery-example but it did not work for me. Has anybody an idea or could help me? (: