W3cubDocs

/webpack 2

imports-loader

Install

npm install imports-loader

Usage

Given you have this file example.js

$("img").doSomeAwesomeJqueryPluginStuff();

then you can inject the $ variable into the module by configuring the imports-loader like this:

require("imports-loader?$=jquery!./example.js");

This simply prepends var $ = require("jquery"); to example.js.

Syntax

Query value
Equals
Query value
angular
Equals
var angular = require("angular");
Query value
$=jquery
Equals
var $ = require("jquery");
Query value
define=>false
Equals
var define = false;
Query value
config=>{size:50}
Equals
var config = {size:50};
Query value
this=>window
Equals
(function () { ... }).call(window);

Multiple values

Multiple values are separated by comma ,:

require("imports-loader?$=jquery,angular,config=>{size:50}!./file.js");

webpack.config.js

As always, you should rather configure this in your webpack.config.js:

// ./webpack.config.js

module.exports = {
    ...
    module: {
        loaders: [
            {
                test: require.resolve("some-module"),
                loader: "imports-loader?this=>window"
            }
        ]
    }
};

Documentation: Using loaders

Typical Use Cases

jQuery plugins

imports-loader?$=jquery

Custom Angular modules

imports-loader?angular

Disable AMD

There are many modules that check for a define function before using CommonJS. Since webpack is capable of both, they default to AMD in this case, which can be a problem if the implementation is quirky.

Then you can easily disable the AMD path by writing

imports-loader?define=>false

For further hints on compatibility issues, check out Shimming Modules of the official docs.

© 2012–2016 Tobias Koppers
Licensed under the Creative Commons Attribution License 4.0.
https://webpack.js.org/loaders/imports-loader/