Simple question about jquery and webpack,
I have downloaded jquery.js
then added into app.js
these lines
import "./jquery";
import "./bootstrap";
My webpack.config
entry line
entry: "./src/app.js"
So files tree is:
./webpack.config.js
./src/app.js
./src/jquery.js
./src/bootstrap.js
How can I simply add jquery
to define in webpack.config
with this file tree while it is functional?
I tried adding
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
})
at the end of the webpack.config
but it gives Module not found: Error: Can't resolve 'jquery'
.
What is the solution for using js files manually with webpack for bundling without an error?
Step 1 :
In general, Webpack is a module bundler.
It allows bundling your own modules (require("./my-module.js")
) as well as thirdparty modules (require("bootstrap")
)
In your case, that would mean you dont have to download the jquery and bootstrap files yourself. Update your package.json
to include the required jquery and bootstrap modules. NPM will take care of getting them and webpack will do the bundling from the node_modules
files.
Step 2 :
In general, webpack needs and entry
point and output
locations. Thats the minimal config it needs.
Once you have an entry
point, webpack still needs to know what dependencies your code needs. Be it your own modules or thirdparty modules (maintained with npm). That is where the require("module-name-or-path")
or import "module-name-or-path"
comes into picture. What that means is that you need to make sure your entry
script has all the required dependencies mentioned either in the same file or in the dependent modules.
To give more insight, webpack looks at the entry
point and will build the dependency graph. It will read all that require()
or import
and pulls in all required modules. It then bundles it.
In your case, the entry script can include the require
statements for jquery and bootstrap npm modules (i.e. thirdparty)
In case, you still need clarity, feel free to go through the code here. Especially take a look at src/entry.js
Note : Bootstrap needs fonts and images as well. The code in repository above, takes care of them too. All the magic done by webpack
!