Webpack (2) — Importing a javascript library
After the small introduction of Webpack, I suggest you to know how to import your libraries (jQuery, Bootstrap, …).
The first library you’ll probably want to use is jQuery.
There are many solutions to include jQuery in your project and I will not explain all of them. Only those that are relevant in my opinion.
The first is just “import it”.
import $ from jquery
But if you do that, you will import the dist version of jQuery and you probably don’t want to include it directly in your bundle. It’s more relevant here to include the source.
Why it includes the dist by default?
When you import/require a Node module (from node_modules folder by default), Webpack search the first key available in package.json among it’s parameter resolve.packageMains whose default value is [“webpack”, “browser”, “web”, “browserify”, [“jam”, “main”], “main”].
For jQuery, it’s main and the corresponding value is dist/jquery.js.
“main”: “dist/jquery.js”,
So, Webpack loads the dist version of jQuery.
To load the source version of jQuery, you can define an alias:
resolve: {
alias: {
jquery: ‘jquery/src/jquery’
}
},With this solution, you benefit of eventual optimizations provided by Webpack on each import (jQuery uses CommonJS too) and especially the deduplication of code. Webpack provides a plugin Dedupe that detect and remove duplication of code… But now I am realizing that jQuery exposes itself on window with the source but not with the dist. It sounds like a leak to me: the aim of import is to organise your code and reduce the risks of collision. If $ is already used in the global space (window in a browser) before loading jQuery, then your code has a serious problem.
A handy tip to complete libraries handling in Webpack is to define a kind of virtual global variable. To do that, just use the internal Webpack plugin ProvidePlugin:
new webpack.ProvidePlugin({
$: “jquery”
})In each chunk, if an occurence of $ is found, jQuery will be required and affected to $. Now you doesn’t need to manually import jQuery anymore :D
Another last thing, useful, is import your favorite SASS library from node_modules folder. You have 2 main solutions.
Configure sass-loader to make it lookup inside node_modules folder:
sassLoader: {
includePaths: [
path.resolve(__dirname, ‘./node_modules/bootstrap-sass/assets/stylesheets/’),
]
},Thus it becomes possible to import any SCSS file from this folder. But in the case of Bootstrap, subsequent imports involve an error while loading fonts. So, for Bootstrap (bootstrap-sass), you must do this:
$bootstrap-sass-asset-helper: true;
@import ‘bootstrap’;
You can read my previous post on Webpack here: Webpack — Another tutorial