lazy
{Boolean}
This package allows transpiling JavaScript files using Babel and webpack.
Note: Issues with the output should be reported on the Babel Issues tracker.
webpack 4.x | babel-loader 8.x | babel 7.x
npm install -D babel-loader @babel/core @babel/preset-env webpack
webpack documentation: Loaders
Within your webpack configuration object, you'll need to add the babel-loader to the list of modules, like so:
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
}
]
}
See the babel
options.
You can pass options to the loader by using the options
property:
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
plugins: ['@babel/plugin-proposal-object-rest-spread']
}
}
}
]
}
This loader also supports the following loader-specific option:
cacheDirectory
: Default false
. When set, the given directory will be used to cache the results of the loader. Future webpack builds will attempt to read from the cache to avoid needing to run the potentially expensive Babel recompilation process on each run. If the value is set to true
in options ({cacheDirectory: true}
), the loader will use the default cache directory in node_modules/.cache/babel-loader
or fallback to the default OS temporary file directory if no node_modules
folder could be found in any root directory.
cacheIdentifier
: Default is a string composed by the @babel/core
's version, the babel-loader
's version, the contents of .babelrc
file if it exists, and the value of the environment variable BABEL_ENV
with a fallback to the NODE_ENV
environment variable. This can be set to a custom value to force cache busting if the identifier changes.
cacheCompression
: Default true
. When set, each Babel transform output will be compressed with Gzip. If you want to opt-out of cache compression, set it to false
-- your project may benefit from this if it transpiles thousands of files.
customize
: Default null
. The path of a module that exports a custom
callback like the one that you'd pass to .custom()
. Since you already have to make a new file to use this, it is recommended that you instead use .custom
to create a wrapper loader. Only use this if you must continue using babel-loader
directly, but still want to customize.
Make sure you are transforming as few files as possible. Because you are probably matching /\.m?js$/
, you might be transforming the node_modules
folder or other unwanted source.
To exclude node_modules
, see the exclude
option in the loaders
config as documented above.
You can also speed up babel-loader by as much as 2x by using the cacheDirectory
option. This will cache transformations to the filesystem.
Babel uses very small helpers for common functions such as _extend
. By default, this will be added to every file that requires it.
You can instead require the Babel runtime as a separate module to avoid the duplication.
The following configuration disables automatic per-file runtime injection in Babel, requiring @babel/plugin-transform-runtime
instead and making all helper references use it.
See the docs for more information.
NOTE: You must run npm install -D @babel/plugin-transform-runtime
to include this in your project and @babel/runtime
itself as a dependency with npm install @babel/runtime
.
rules: [
// the 'transform-runtime' plugin tells Babel to
// require the runtime instead of inlining it.
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
plugins: ['@babel/plugin-transform-runtime']
}
}
}
]
Since @babel/plugin-transform-runtime includes a polyfill that includes a custom regenerator-runtime and core-js, the following usual shimming method using webpack.ProvidePlugin
will not work:
// ...
new webpack.ProvidePlugin({
'Promise': 'bluebird'
}),
// ...
The following approach will not work either:
require('@babel/runtime/core-js/promise').default = require('bluebird');
var promise = new Promise;
which outputs to (using runtime
):
'use strict';
var _Promise = require('@babel/runtime/core-js/promise')['default'];
require('@babel/runtime/core-js/promise')['default'] = require('bluebird');
var promise = new _Promise();
The previous Promise
library is referenced and used before it is overridden.
One approach is to have a "bootstrap" step in your application that would first override the default globals before your application:
// bootstrap.js
require('@babel/runtime/core-js/promise').default = require('bluebird');
// ...
require('./app');
babel
has been moved to babel-core
.If you receive this message, it means that you have the npm package babel
installed and are using the short notation of the loader in the webpack config (which is not valid anymore as of webpack 2.x):
{
test: /\.m?js$/,
loader: 'babel',
}
webpack then tries to load the babel
package instead of the babel-loader
.
To fix this, you should uninstall the npm package babel
, as it is deprecated in Babel v6. (Instead, install @babel/cli
or @babel/core
.)
In the case one of your dependencies is installing babel
and you cannot uninstall it yourself, use the complete name of the loader in the webpack config:
{
test: /\.m?js$/,
loader: 'babel-loader',
}
core-js
and webpack/buildin
will cause errors if they are transpiled by Babel.
You will need to exclude them form babel-loader
.
{
"loader": "babel-loader",
"options": {
"exclude": [
// \\ for Windows, \/ for Mac OS and Linux
/node_modules[\\\/]core-js/,
/node_modules[\\\/]webpack[\\\/]buildin/,
],
"presets": [
"@babel/preset-env"
]
}
}
Webpack supports bundling multiple targets. For cases where you may want different Babel configurations for each target (like web
and node
), this loader provides a target
property via Babel's caller API.
For example, to change the environment targets passed to @babel/preset-env
based on the webpack target:
// babel.config.js
module.exports = api => {
return {
plugins: [
"@babel/plugin-proposal-nullish-coalescing-operator",
"@babel/plugin-proposal-optional-chaining"
],
presets: [
[
"@babel/preset-env",
{
useBuiltIns: "entry",
// caller.target will be the same as the target option from webpack
targets: api.caller(caller => caller && caller.target === "node")
? { node: "current" }
: { chrome: "58", ie: "11" }
}
]
]
}
}
babel-loader
exposes a loader-builder utility that allows users to add custom handling
of Babel's configuration for each file that it processes.
.custom
accepts a callback that will be called with the loader's instance of
babel
so that tooling can ensure that it using exactly the same @babel/core
instance as the loader itself.
In cases where you want to customize without actually having a file to call .custom
, you
may also pass the customize
option with a string pointing at a file that exports
your custom
callback function.
// Export from "./my-custom-loader.js" or whatever you want.
module.exports = require("babel-loader").custom(babel => {
function myPlugin() {
return {
visitor: {},
};
}
return {
// Passed the loader options.
customOptions({ opt1, opt2, ...loader }) {
return {
// Pull out any custom options that the loader might have.
custom: { opt1, opt2 },
// Pass the options back with the two custom options removed.
loader,
};
},
// Passed Babel's 'PartialConfig' object.
config(cfg) {
if (cfg.hasFilesystemConfig()) {
// Use the normal config
return cfg.options;
}
return {
...cfg.options,
plugins: [
...(cfg.options.plugins || []),
// Include a custom plugin in the options.
myPlugin,
],
};
},
result(result) {
return {
...result,
code: result.code + "\n// Generated by some custom loader",
};
},
};
});
// And in your Webpack config
module.exports = {
// ..
module: {
rules: [{
// ...
loader: path.join(__dirname, 'my-custom-loader.js'),
// ...
}]
}
};
customOptions(options: Object): { custom: Object, loader: Object }
Given the loader's options, split custom options out of babel-loader
's
options.
config(cfg: PartialConfig): Object
Given Babel's PartialConfig
object, return the options
object that should
be passed to babel.transform
.
result(result: Result): Result
Given Babel's result object, allow loaders to make additional tweaks to it.
Bundle loader for webpack
npm i bundle-loader --save
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.bundle\.js$/,
use: 'bundle-loader'
}
]
}
}
The chunk is requested, when you require the bundle.
file.js
import bundle from './file.bundle.js';
To wait until the chunk is available (and get the exports) you need to async wait for it.
bundle((file) => {
// use the file like it was required
const file = require('./file.js')
});
This wraps the require('file.js')
in a require.ensure
block
Multiple callbacks can be added. They will be executed in the order of addition.
bundle(callbackTwo)
bundle(callbackThree)
If a callback is added after dependencies were loaded, it will be called immediately.
Name | Type | Default | Description |
---|---|---|---|
Name Type Default Description
|
{Boolean} |
false |
Loads the imported bundle asynchronously |
Name Type Default Description
|
{String} |
[id].[name] |
Configure a custom filename for your imported bundle |
lazy
The file is requested when you require the bundle-loader
. If you want it to request it lazy, use:
webpack.config.js
{
loader: 'bundle-loader',
options: {
lazy: true
}
}
import bundle from './file.bundle.js'
bundle((file) => {...})
ℹ️ The chunk is not requested until you call the load function
name
You may set name for a bundle using the name
options parameter.
See documentation.
webpack.config.js
{
loader: 'bundle-loader',
options: {
name: '[name]'
}
}
:warning: chunks created by the loader will be named according to the
output.chunkFilename
rule, which defaults to[id].[name]
. Here[name]
corresponds to the chunk name set in thename
options parameter.
import bundle from './file.bundle.js'
webpack.config.js
module.exports = {
entry: {
index: './App.js'
},
output: {
path: path.resolve(__dirname, 'dest'),
filename: '[name].js',
// or whatever other format you want
chunkFilename: '[name].[id].js',
},
module: {
rules: [
{
test: /\.bundle\.js$/,
use: {
loader: 'bundle-loader',
options: {
name: 'my-chunk'
}
}
}
]
}
}
Normal chunks will show up using the filename
rule above, and be named according to their [chunkname]
.
Chunks from bundle-loader
, however will load using the chunkFilename
rule, so the example files will produce my-chunk.1.js
and file-2.js
respectively.
You can also use chunkFilename
to add hash values to the filename, since putting [hash]
in the bundle options parameter does not work correctly.
Juho Vepsäläinen | Joshua Wiens | Michael Ciniawsky | Alexander Krasnoyarov |
The cache-loader
allow to Caches the result of following loaders on disk (default) or in the database.
To begin, you'll need to install cache-loader
:
npm install --save-dev cache-loader
Add this loader in front of other (expensive) loaders to cache the result on disk.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.ext$/,
use: ['cache-loader', ...loaders],
include: path.resolve('src'),
},
],
},
};
⚠️ Note that there is an overhead for saving the reading and saving the cache file, so only use this loader to cache expensive loaders.
Name | Type | n Default | Description |
---|---|---|---|
Name Type n Default Description
|
{String} |
undefined |
Allows you to override the default cache context in order to generate the cache relatively to a path. By default it will use absolute paths |
Name Type n Default Description
|
{Function(options, request) -> {String}} |
undefined |
Allows you to override default cache key generator |
Name Type n Default Description
|
{String} |
findCacheDir({ name: 'cache-loader' }) or os.tmpdir() |
Provide a cache directory where cache items should be stored (used for default read/write implementation) |
Name Type n Default Description
|
{String} |
cache-loader:{version} {process.env.NODE_ENV} |
Provide an invalidation identifier which is used to generate the hashes. You can use it for extra dependencies of loaders (used for default read/write implementation) |
Name Type n Default Description
|
{Function(stats, dep) -> {Boolean}} |
undefined |
Allows you to override default comparison function between the cached dependency and the one is being read. Return
true
to use the cached resource |
Name Type n Default Description
|
{Number} |
0 |
Round
mtime
by this number of milliseconds both for
stats
and
dep
before passing those params to the comparing function |
Name Type n Default Description
|
{Function(cacheKey, callback) -> {void}} |
undefined |
Allows you to override default read cache data from file |
Name Type n Default Description
|
{Boolean} |
false |
Allows you to override default value and make the cache read only (useful for some environments where you don't want the cache to be updated, only read from it) |
Name Type n Default Description
|
{Function(cacheKey, data, callback) -> {void}} |
undefined |
Allows you to override default write cache data to file (e.g. Redis, memcached) |
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.js$/,
use: ['cache-loader', 'babel-loader'],
include: path.resolve('src'),
},
],
},
};
webpack.config.js
// Or different database client - memcached, mongodb, ...
const redis = require('redis');
const crypto = require('crypto');
// ...
// connect to client
// ...
const BUILD_CACHE_TIMEOUT = 24 * 3600; // 1 day
function digest(str) {
return crypto
.createHash('md5')
.update(str)
.digest('hex');
}
// Generate own cache key
function cacheKey(options, request) {
return `build:cache:${digest(request)}`;
}
// Read data from database and parse them
function read(key, callback) {
client.get(key, (err, result) => {
if (err) {
return callback(err);
}
if (!result) {
return callback(new Error(`Key ${key} not found`));
}
try {
let data = JSON.parse(result);
callback(null, data);
} catch (e) {
callback(e);
}
});
}
// Write data to database under cacheKey
function write(key, data, callback) {
client.set(key, JSON.stringify(data), 'EX', BUILD_CACHE_TIMEOUT, callback);
}
module.exports = {
module: {
rules: [
{
test: /\.js$/,
use: [
{
loader: 'cache-loader',
options: {
cacheKey,
read,
write,
},
},
'babel-loader',
],
include: path.resolve('src'),
},
],
},
};
Please take a moment to read our contributing guidelines if you haven't yet done so.
Compile CoffeeScript to JavaScript.
To begin, you'll need to install coffeescript
and coffee-loader
:
npm install --save-dev coffeescript coffee-loader
Then add the plugin to your webpack
config. For example:
file.coffee
# Assignment:
number = 42
opposite = true
# Conditions:
number = -42 if opposite
# Functions:
square = (x) -> x * x
# Arrays:
list = [1, 2, 3, 4, 5]
# Objects:
math =
root: Math.sqrt
square: square
cube: (x) -> x * square x
# Splats:
race = (winner, runners...) ->
print winner, runners
# Existence:
alert "I knew it!" if elvis?
# Array comprehensions:
cubes = (math.cube num for num in list)
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.coffee$/,
loader: "coffee-loader",
},
],
},
};
Alternative usage:
import coffee from "coffee-loader!./file.coffee";
And run webpack
via your preferred method.
Type: Object
Default: { bare: true }
Options for CoffeeScript. All possible options you can find here.
Documentation for the transpile
option you can find here.
ℹ️ The
sourceMap
option takes a value from thecompiler.devtool
value by default.ℹ️ The
filename
option takes a value from webpack loader API. The option value will be ignored.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.coffee$/,
loader: "coffee-loader",
options: {
bare: false,
transpile: {
presets: ["@babel/env"],
},
},
},
],
},
};
From CoffeeScript 2 documentation:
CoffeeScript 2 generates JavaScript that uses the latest, modern syntax. The runtime or browsers where you want your code to run might not support all of that syntax. In that case, we want to convert modern JavaScript into older JavaScript that will run in older versions of Node or older browsers; for example,
{ a } = obj
intoa = obj.a
. This is done via transpilers like Babel, Bublé or Traceur Compiler.
You'll need to install @babel/core
and @babel/preset-env
and then create a configuration file:
npm install --save-dev @babel/core @babel/preset-env
echo '{ "presets": ["@babel/env"] }' > .babelrc
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.coffee$/,
loader: "coffee-loader",
options: {
transpile: {
presets: ["@babel/env"],
},
},
},
],
},
};
For using Literate CoffeeScript you should setup:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.coffee$/,
loader: "coffee-loader",
options: {
literate: true,
},
},
],
},
};
Please take a moment to read our contributing guidelines if you haven't yet done so.
Coffee Script Redux loader for Webpack.
npm i -D coffee-redux-loader
var exportsOfFile = require("coffee-redux-loader!./file.coffee");
// => return exports of executed and compiled file.coffee
Don't forget to polyfill require
if you want to use it in node.
See webpack
documentation.
Juho Vepsäläinen | Joshua Wiens | Kees Kluskens | Sean Larkin |
webpack-dev-server "mocha!./cover-my-client-tests.js" --options webpackOptions.js
// webpackOptions.js
module.exports = {
// your webpack options
output: "bundle.js",
publicPrefix: "/",
debug: true,
includeFilenames: true,
watch: true,
// the coverjs loader binding
postLoaders: [{
test: "", // every file
exclude: [
"node_modules.chai",
"node_modules.coverjs-loader",
"node_modules.webpack.buildin"
],
loader: "coverjs-loader"
}]
}
// cover-my-client-tests.js
require("./my-client-tests");
after(function() {
require("cover-loader").reportHtml();
});
See the-big-test for an example.
You don't have to combine it with the mocha loader, it's independent. So if you want to cover a normal app usage, you can do so. The reportHtml
function just appends the output to the body.
MIT (http://www.opensource.org/licenses/mit-license.php)
The css-loader
interprets @import
and url()
like import/require()
and will resolve them.
⚠ To use css-loader, webpack@5 is required
To begin, you'll need to install css-loader
:
npm install --save-dev css-loader
Then add the plugin to your webpack
config. For example:
file.js
import css from "file.css";
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
],
},
};
And run webpack
via your preferred method.
If, for one reason or another, you need to extract CSS as a file (i.e. do not store CSS in a JS module) you might want to check out the recommend example.
Name | Type | Default | Description |
---|---|---|---|
Name Type Default Description
|
{Boolean\|Object} |
true |
Allows to enables/disables
url()
/
image-set()
functions handling |
Name Type Default Description
|
{Boolean\|Object} |
true |
Allows to enables/disables
@import
at-rules handling |
Name Type Default Description
|
{Boolean\|String\|Object} |
{auto: true} |
Allows to enables/disables or setup CSS Modules options |
Name Type Default Description
|
{Boolean} |
compiler.devtool |
Enables/Disables generation of source maps |
Name Type Default Description
|
{Number} |
0 |
Allows enables/disables or setups number of loaders applied before CSS loader for
@import
/CSS Modules and ICSS imports |
Name Type Default Description
|
{Boolean} |
true |
Use ES modules syntax |
Name Type Default Description
|
{'array' \| 'string' \| 'css-style-sheet'} |
array |
Allows exporting styles as array with modules, string or
constructable stylesheet
(i.e.
CSSStyleSheet
) |
url
Type: Boolean|Object
Default: true
Allow to enable/disables handling the CSS functions url
and image-set
.
If set to false
, css-loader
will not parse any paths specified in url
or image-set
.
A function can also be passed to control this behavior dynamically based on the path to the asset.
Starting with version 4.0.0, absolute paths are parsed based on the server root.
Examples resolutions:
url(image.png) => require('./image.png')
url('image.png') => require('./image.png')
url(./image.png) => require('./image.png')
url('./image.png') => require('./image.png')
url('http://dontwritehorriblecode.com/2112.png') => require('http://dontwritehorriblecode.com/2112.png')
image-set(url('image2x.png') 1x, url('image1x.png') 2x) => require('./image1x.png') and require('./image2x.png')
To import assets from a node_modules
path (include resolve.modules
) and for alias
, prefix it with a ~
:
url(~module/image.png) => require('module/image.png')
url('~module/image.png') => require('module/image.png')
url(~aliasDirectory/image.png) => require('otherDirectory/image.png')
Boolean
Enable/disable url()
resolving.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
url: true,
},
},
],
},
};
Object
Allow to filter url()
. All filtered url()
will not be resolved (left in the code as they were written).
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
url: {
filter: (url, resourcePath) => {
// resourcePath - path to css file
// Don't handle `img.png` urls
if (url.includes("img.png")) {
return false;
}
return true;
},
},
},
},
],
},
};
import
Type: Boolean|Object
Default: true
Allows to enables/disables @import
at-rules handling.
Control @import
resolving. Absolute urls in @import
will be moved in runtime code.
Examples resolutions:
@import 'style.css' => require('./style.css')
@import url(style.css) => require('./style.css')
@import url('style.css') => require('./style.css')
@import './style.css' => require('./style.css')
@import url(./style.css) => require('./style.css')
@import url('./style.css') => require('./style.css')
@import url('http://dontwritehorriblecode.com/style.css') => @import url('http://dontwritehorriblecode.com/style.css') in runtime
To import styles from a node_modules
path (include resolve.modules
) and for alias
, prefix it with a ~
:
@import url(~module/style.css) => require('module/style.css')
@import url('~module/style.css') => require('module/style.css')
@import url(~aliasDirectory/style.css) => require('otherDirectory/style.css')
Boolean
Enable/disable @import
resolving.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
import: true,
},
},
],
},
};
Object
Name | Type | Default | Description |
---|---|---|---|
Name Type Default Description
|
{Function} |
undefined |
Allow to filter
@import |
filter
Type: Function
Default: undefined
Allow to filter @import
. All filtered @import
will not be resolved (left in the code as they were written).
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
import: {
filter: (url, media, resourcePath) => {
// resourcePath - path to css file
// Don't handle `style.css` import
if (url.includes("style.css")) {
return false;
}
return true;
},
},
},
},
],
},
};
modules
Type: Boolean|String|Object
Default: undefined
Allows to enable/disable CSS Modules or ICSS and setup configuration:
undefined
- enable CSS modules for all files matching /\.module\.\w+$/i.test(filename)
and /\.icss\.\w+$/i.test(filename)
regexp.true
- enable CSS modules for all files.false
- disables CSS Modules for all files.string
- disables CSS Modules for all files and set the mode
option, more information you can read hereobject
- enable CSS modules for all files, if modules.auto
option is not specified, otherwise the modules.auto
option will determine whether if it is CSS modules or not, more information you can read hereThe modules
option enables/disables the CSS Modules specification and setup basic behaviour.
Using false
value increase performance because we avoid parsing CSS Modules features, it will be useful for developers who use vanilla css or use other technologies.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
modules: true,
},
},
],
},
};
Features
Scope
Using local
value requires you to specify :global
classes.
Using global
value requires you to specify :local
classes.
Using pure
value requires selectors must contain at least one local class or id.
You can find more information here.
Styles can be locally scoped to avoid globally scoping styles.
The syntax :local(.className)
can be used to declare className
in the local scope. The local identifiers are exported by the module.
With :local
(without brackets) local mode can be switched on for this selector.
The :global(.className)
notation can be used to declare an explicit global selector.
With :global
(without brackets) global mode can be switched on for this selector.
The loader replaces local selectors with unique identifiers. The chosen unique identifiers are exported by the module.
:local(.className) {
background: red;
}
:local .className {
color: green;
}
:local(.className .subClass) {
color: green;
}
:local .className .subClass :global(.global-class-name) {
color: blue;
}
._23_aKvs-b8bW2Vg3fwHozO {
background: red;
}
._23_aKvs-b8bW2Vg3fwHozO {
color: green;
}
._23_aKvs-b8bW2Vg3fwHozO ._13LGdX8RMStbBE9w-t0gZ1 {
color: green;
}
._23_aKvs-b8bW2Vg3fwHozO ._13LGdX8RMStbBE9w-t0gZ1 .global-class-name {
color: blue;
}
ℹ️ Identifiers are exported
exports.locals = {
className: "_23_aKvs-b8bW2Vg3fwHozO",
subClass: "_13LGdX8RMStbBE9w-t0gZ1",
};
CamelCase is recommended for local selectors. They are easier to use within the imported JS module.
You can use :local(#someId)
, but this is not recommended. Use classes instead of ids.
Composing
When declaring a local classname you can compose a local class from another local classname.
:local(.className) {
background: red;
color: yellow;
}
:local(.subClass) {
composes: className;
background: blue;
}
This doesn't result in any change to the CSS itself but exports multiple classnames.
exports.locals = {
className: "_23_aKvs-b8bW2Vg3fwHozO",
subClass: "_13LGdX8RMStbBE9w-t0gZ1 _23_aKvs-b8bW2Vg3fwHozO",
};
._23_aKvs-b8bW2Vg3fwHozO {
background: red;
color: yellow;
}
._13LGdX8RMStbBE9w-t0gZ1 {
background: blue;
}
Importing
To import a local classname from another module.
i We strongly recommend that you specify the extension when importing a file, since it is possible to import a file with any extension and it is not known in advance which file to use.
:local(.continueButton) {
composes: button from "library/button.css";
background: red;
}
:local(.nameEdit) {
composes: edit highlight from "./edit.css";
background: red;
}
To import from multiple modules use multiple composes:
rules.
:local(.className) {
composes: edit hightlight from "./edit.css";
composes: button from "module/button.css";
composes: classFromThisModule;
background: red;
}
Values
You can use @value
to specific values to be reused throughout a document.
We recommend use prefix v-
for values, s-
for selectors and m-
for media at-rules.
@value v-primary: #BF4040;
@value s-black: black-selector;
@value m-large: (min-width: 960px);
.header {
color: v-primary;
padding: 0 10px;
}
.s-black {
color: black;
}
@media m-large {
.header {
padding: 0 20px;
}
}
Boolean
Enable CSS Modules features.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
modules: true,
},
},
],
},
};
String
Enable CSS Modules features and setup mode
.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
// Using `local` value has same effect like using `modules: true`
modules: "global",
},
},
],
},
};
Object
Enable CSS Modules features and setup options for them.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
modules: {
mode: "local",
auto: true,
exportGlobals: true,
localIdentName: "[path][name]__[local]--[hash:base64:5]",
localIdentContext: path.resolve(__dirname, "src"),
localIdentHashSalt: "my-custom-hash",
namedExport: true,
exportLocalsConvention: "camelCase",
exportOnlyLocals: false,
},
},
},
],
},
};
auto
Type: Boolean|RegExp|Function
Default: undefined
Allows auto enable CSS modules/ICSS based on filename when modules
option is object.
Possible values:
undefined
- enable CSS modules for all files.true
- enable CSS modules for all files matching /\.module\.\w+$/i.test(filename)
and /\.icss\.\w+$/i.test(filename)
regexp.false
- disables CSS Modules.RegExp
- enable CSS modules for all files matching /RegExp/i.test(filename)
regexp.function
- enable CSS Modules for files based on the filename satisfying your filter function check.Boolean
Possible values:
true
- enables CSS modules or interoperable CSS format, sets the modules.mode
option to local
value for all files which satisfy /\.module(s)?\.\w+$/i.test(filename)
condition or sets the modules.mode
option to icss
value for all files which satisfy /\.icss\.\w+$/i.test(filename)
conditionfalse
- disables CSS modules or interoperable CSS format based on filenamewebpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
modules: {
auto: true,
},
},
},
],
},
};
RegExp
Enable css modules for files based on the filename satisfying your regex check.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
modules: {
auto: /\.custom-module\.\w+$/i,
},
},
},
],
},
};
Function
Enable css modules for files based on the filename satisfying your filter function check.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
modules: {
auto: (resourcePath) => resourcePath.endsWith(".custom-module.css"),
},
},
},
],
},
};
mode
Type: String|Function
Default: 'local'
Setup mode
option. You can omit the value when you want local
mode.
Controls the level of compilation applied to the input styles.
The local
, global
, and pure
handles class
and id
scoping and @value
values.
The icss
will only compile the low level Interoperable CSS
format for declaring :import
and :export
dependencies between CSS and other languages.
ICSS underpins CSS Module support, and provides a low level syntax for other tools to implement CSS-module variations of their own.
String
Possible values - local
, global
, pure
, and icss
.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
modules: {
mode: "global",
},
},
},
],
},
};
Function
Allows set different values for the mode
option based on a filename
Possible return values - local
, global
, pure
and icss
.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
modules: {
// Callback must return "local", "global", or "pure" values
mode: (resourcePath) => {
if (/pure.css$/i.test(resourcePath)) {
return "pure";
}
if (/global.css$/i.test(resourcePath)) {
return "global";
}
return "local";
},
},
},
},
],
},
};
localIdentName
Type: String
Default: '[hash:base64]'
Allows to configure the generated local ident name.
For more information on options see:
Supported template strings:
[name]
the basename of the resource[folder]
the folder the resource relative to the compiler.context
option or modules.localIdentContext
option.[path]
the path of the resource relative to the compiler.context
option or modules.localIdentContext
option.[file]
- filename and path.[ext]
- extension with leading .
.[hash]
- the hash of the string, generated based on localIdentHashSalt
, localIdentHashFunction
, localIdentHashDigest
, localIdentHashDigestLength
, localIdentContext
, resourcePath
and exportName
[<hashFunction>:hash:<hashDigest>:<hashDigestLength>]
- hash with hash settings.[local]
- original class.Recommendations:
'[path][name]__[local]'
for development'[hash:base64]'
for productionThe [local]
placeholder contains original class.
Note: all reserved (<>:"/\|?*
) and control filesystem characters (excluding characters in the [local]
placeholder) will be converted to -
.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
modules: {
localIdentName: "[path][name]__[local]--[hash:base64:5]",
},
},
},
],
},
};
localIdentContext
Type: String
Default: compiler.context
Allows to redefine basic loader context for local ident name.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
modules: {
localIdentContext: path.resolve(__dirname, "src"),
},
},
},
],
},
};
localIdentHashSalt
Type: String
Default: undefined
Allows to add custom hash to generate more unique classes. For more information see output.hashSalt.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
modules: {
localIdentHashSalt: "hash",
},
},
},
],
},
};
localIdentHashFunction
Type: String
Default: md4
Allows to specify hash function to generate classes . For more information see output.hashFunction.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
modules: {
localIdentHashFunction: "md4",
},
},
},
],
},
};
localIdentHashDigest
Type: String
Default: hex
Allows to specify hash digest to generate classes. For more information see output.hashDigest.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
modules: {
localIdentHashDigest: "base64",
},
},
},
],
},
};
localIdentHashDigestLength
Type: Number
Default: 20
Allows to specify hash digest length to generate classes. For more information see output.hashDigestLength.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
modules: {
localIdentHashDigestLength: 5,
},
},
},
],
},
};
localIdentRegExp
Type: String|RegExp
Default: undefined
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
modules: {
localIdentRegExp: /page-(.*)\.css/i,
},
},
},
],
},
};
getLocalIdent
Type: Function
Default: undefined
Allows to specify a function to generate the classname.
By default we use built-in function to generate a classname.
If the custom function returns null
or undefined
, we fallback to the
built-in function to generate the classname.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
modules: {
getLocalIdent: (context, localIdentName, localName, options) => {
return "whatever_random_class_name";
},
},
},
},
],
},
};
namedExport
Type: Boolean
Default: false
Enables/disables ES modules named export for locals.
⚠ Names of locals are converted to camelcase, i.e. the
exportLocalsConvention
option hascamelCaseOnly
value by default.⚠ It is not allowed to use JavaScript reserved words in css class names.
styles.css
.foo-baz {
color: red;
}
.bar {
color: blue;
}
index.js
import { fooBaz, bar } from "./styles.css";
console.log(fooBaz, bar);
You can enable a ES module named export using:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
esModule: true,
modules: {
namedExport: true,
},
},
},
],
},
};
To set a custom name for namedExport, can use exportLocalsConvention
option as a function.
Example below in the examples
section.
exportGlobals
Type: Boolean
Default: false
Allow css-loader
to export names from global class or id, so you can use that as local name.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
modules: {
exportGlobals: true,
},
},
},
],
},
};
exportLocalsConvention
Type: String|Function
Default: based on the modules.namedExport
option value, if true
- camelCaseOnly
, otherwise asIs
Style of exported class names.
String
By default, the exported JSON keys mirror the class names (i.e asIs
value).
⚠ Only
camelCaseOnly
value allowed if you set thenamedExport
value totrue
.
Name | Type | Description |
---|---|---|
Name Type Description
|
{String} |
Class names will be exported as is. |
Name Type Description
|
{String} |
Class names will be camelized, the original class name will not to be removed from the locals |
Name Type Description
|
{String} |
Class names will be camelized, the original class name will be removed from the locals |
Name Type Description
|
{String} |
Only dashes in class names will be camelized |
Name Type Description
|
{String} |
Dashes in class names will be camelized, the original class name will be removed from the locals |
file.css
.class-name {
}
file.js
import { className } from "file.css";
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
modules: {
exportLocalsConvention: "camelCase",
},
},
},
],
},
};
Function
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
modules: {
exportLocalsConvention: function (name) {
return name.replace(/-/g, "_");
},
},
},
},
],
},
};
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
modules: {
exportLocalsConvention: function (name) {
return [
name.replace(/-/g, "_"),
// dashesCamelCase
name.replace(/-+(\w)/g, (match, firstLetter) =>
firstLetter.toUpperCase()
),
];
},
},
},
},
],
},
};
exportOnlyLocals
Type: Boolean
Default: false
Export only locals.
Useful when you use css modules for pre-rendering (for example SSR).
For pre-rendering with mini-css-extract-plugin
you should use this option instead of style-loader!css-loader
in the pre-rendering bundle.
It doesn't embed CSS but only exports the identifier mappings.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
modules: {
exportOnlyLocals: true,
},
},
},
],
},
};
importLoaders
Type: Number
Default: 0
Allows to enables/disables or setups number of loaders applied before CSS loader for @import
at-rules, CSS modules and ICSS imports, i.e. @import
/composes
/@value value from './values.css'
/etc.
The option importLoaders
allows you to configure how many loaders before css-loader
should be applied to @import
ed resources and CSS modules/ICSS imports.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
"style-loader",
{
loader: "css-loader",
options: {
importLoaders: 2,
// 0 => no loaders (default);
// 1 => postcss-loader;
// 2 => postcss-loader, sass-loader
},
},
"postcss-loader",
"sass-loader",
],
},
],
},
};
This may change in the future when the module system (i. e. webpack) supports loader matching by origin.
sourceMap
Type: Boolean
Default: depends on the compiler.devtool
value
By default generation of source maps depends on the devtool
option. All values enable source map generation except eval
and false
value.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
sourceMap: true,
},
},
],
},
};
esModule
Type: Boolean
Default: true
By default, css-loader
generates JS modules that use the ES modules syntax.
There are some cases in which using ES modules is beneficial, like in the case of module concatenation and tree shaking.
You can enable a CommonJS modules syntax using:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
esModule: false,
},
},
],
},
};
exportType
Type: 'array' | 'string' | 'css-style-sheet'
Default: 'array'
Allows exporting styles as array with modules, string or constructable stylesheet (i.e. CSSStyleSheet
).
Default value is 'array'
, i.e. loader exports array of modules with specific API which is used in style-loader
or other.
webpack.config.js
module.exports = {
module: {
rules: [
{
assert: { type: "css" },
loader: "css-loader",
options: {
exportType: "css-style-sheet",
},
},
],
},
};
src/index.js
import sheet from "./styles.css" assert { type: "css" };
document.adoptedStyleSheets = [sheet];
shadowRoot.adoptedStyleSheets = [sheet];
'array'
The default export is array of modules with specific API which is used in style-loader
or other.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/i,
use: ["style-loader", "css-loader", "postcss-loader", "sass-loader"],
},
],
},
};
src/index.js
// `style-loader` applies styles to DOM
import "./styles.css";
'string'
⚠ You don't need
style-loader
anymore, please remove it. ⚠ TheesModules
option should be enabled if you want to use it withCSS modules
, by default for locals will be used named export.
The default export is string
.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/i,
use: ["css-loader", "postcss-loader", "sass-loader"],
},
],
},
};
src/index.js
import sheet from "./styles.css";
console.log(sheet);
'css-style-sheet'
⚠
@import
rules not yet allowed, more information ⚠ You don't needstyle-loader
anymore, please remove it. ⚠ TheesModules
option should be enabled if you want to use it withCSS modules
, by default for locals will be used named export. ⚠ Source maps are not currently supported inChrome
due bug
The default export is a constructable stylesheet (i.e. CSSStyleSheet
).
Useful for custom elements and shadow DOM.
More information:
webpack.config.js
module.exports = {
module: {
rules: [
{
assert: { type: "css" },
loader: "css-loader",
options: {
exportType: "css-style-sheet",
},
},
// For Sass/SCSS:
//
// {
// assert: { type: "css" },
// rules: [
// {
// loader: "css-loader",
// options: {
// exportType: "css-style-sheet",
// // Other options
// },
// },
// {
// loader: "sass-loader",
// options: {
// // Other options
// },
// },
// ],
// },
],
},
};
src/index.js
// Example for Sass/SCSS:
// import sheet from "./styles.scss" assert { type: "css" };
// Example for CSS modules:
// import sheet, { myClass } from "./styles.scss" assert { type: "css" };
// Example for CSS:
import sheet from "./styles.css" assert { type: "css" };
document.adoptedStyleSheets = [sheet];
shadowRoot.adoptedStyleSheets = [sheet];
For migration purposes, you can use the following configuration:
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
oneOf: [
{
assert: { type: "css" },
loader: "css-loader",
options: {
exportType: "css-style-sheet",
// Other options
},
},
{
use: [
"style-loader",
{
loader: "css-loader",
options: {
// Other options
},
},
],
},
],
},
],
},
};
For production
builds it's recommended to extract the CSS from your bundle being able to use parallel loading of CSS/JS resources later on.
This can be achieved by using the mini-css-extract-plugin, because it creates separate css files.
For development
mode (including webpack-dev-server
) you can use style-loader, because it injects CSS into the DOM using multiple and works faster.
i Do not use together
style-loader
andmini-css-extract-plugin
.
webpack.config.js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const devMode = process.env.NODE_ENV !== "production";
module.exports = {
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/i,
use: [
devMode ? "style-loader" : MiniCssExtractPlugin.loader,
"css-loader",
"postcss-loader",
"sass-loader",
],
},
],
},
plugins: [].concat(devMode ? [] : [new MiniCssExtractPlugin()]),
};
/* webpackIgnore: true */
commentWith the help of the /* webpackIgnore: true */
comment, it is possible to disable sources handling for rules and for individual declarations.
/* webpackIgnore: true */
@import url(./basic.css);
@import /* webpackIgnore: true */ url(./imported.css);
.class {
/* Disabled url handling for the all urls in the 'background' declaration */
color: red;
/* webpackIgnore: true */
background: url("./url/img.png"), url("./url/img.png");
}
.class {
/* Disabled url handling for the first url in the 'background' declaration */
color: red;
background:
/* webpackIgnore: true */ url("./url/img.png"), url("./url/img.png");
}
.class {
/* Disabled url handling for the second url in the 'background' declaration */
color: red;
background: url("./url/img.png"),
/* webpackIgnore: true */ url("./url/img.png");
}
/* prettier-ignore */
.class {
/* Disabled url handling for the second url in the 'background' declaration */
color: red;
background: url("./url/img.png"),
/* webpackIgnore: true */
url("./url/img.png");
}
/* prettier-ignore */
.class {
/* Disabled url handling for third and sixth urls in the 'background-image' declaration */
background-image: image-set(
url(./url/img.png) 2x,
url(./url/img.png) 3x,
/* webpackIgnore: true */ url(./url/img.png) 4x,
url(./url/img.png) 5x,
url(./url/img.png) 6x,
/* webpackIgnore: true */
url(./url/img.png) 7x
);
}
The following webpack.config.js
can load CSS files, embed small PNG/JPG/GIF/SVG images as well as fonts as Data URLs and copy larger files to the output directory.
For webpack v5:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
{
test: /\.(png|jpe?g|gif|svg|eot|ttf|woff|woff2)$/i,
// More information here https://webpack.js.org/guides/asset-modules/
type: "asset",
},
],
},
};
For production builds it's recommended to extract the CSS from your bundle being able to use parallel loading of CSS/JS resources later on.
This can be achieved by using the mini-css-extract-plugin to extract the CSS when running in production mode.
As an alternative, if seeking better development performance and css outputs that mimic production. extract-css-chunks-webpack-plugin offers a hot module reload friendly, extended version of mini-css-extract-plugin. HMR real CSS files in dev, works like mini-css in non-dev
When you have pure CSS (without CSS modules), CSS modules and PostCSS in your project you can use this setup:
webpack.config.js
module.exports = {
module: {
rules: [
{
// For pure CSS - /\.css$/i,
// For Sass/SCSS - /\.((c|sa|sc)ss)$/i,
// For Less - /\.((c|le)ss)$/i,
test: /\.((c|sa|sc)ss)$/i,
use: [
"style-loader",
{
loader: "css-loader",
options: {
// Run `postcss-loader` on each CSS `@import` and CSS modules/ICSS imports, do not forget that `sass-loader` compile non CSS `@import`'s into a single file
// If you need run `sass-loader` and `postcss-loader` on each CSS `@import` please set it to `2`
importLoaders: 1,
},
},
{
loader: "postcss-loader",
options: { plugins: () => [postcssPresetEnv({ stage: 0 })] },
},
// Can be `less-loader`
{
loader: "sass-loader",
},
],
},
// For webpack v5
{
test: /\.(png|jpe?g|gif|svg|eot|ttf|woff|woff2)$/i,
// More information here https://webpack.js.org/guides/asset-modules/
type: "asset",
},
],
},
};
index.css
.class {
background: url(/assets/unresolved/img.png);
}
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
],
},
resolve: {
alias: {
"/assets/unresolved/img.png": path.resolve(
__dirname,
"assets/real-path-to-img/img.png"
),
},
},
};
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "css-loader",
options: {
modules: {
namedExport: true,
exportLocalsConvention: function (name) {
return name.replace(/-/g, "_");
},
},
},
},
],
},
};
Interoperable CSS
-only and CSS Module
featuresThe following setup is an example of allowing Interoperable CSS
features only (such as :import
and :export
) without using further CSS Module
functionality by setting mode
option for all files that do not match *.module.scss
naming convention. This is for reference as having ICSS
features applied to all files was default css-loader
behavior before v4.
Meanwhile all files matching *.module.scss
are treated as CSS Modules
in this example.
An example case is assumed where a project requires canvas drawing variables to be synchronized with CSS - canvas drawing uses the same color (set by color name in JavaScript) as HTML background (set by class name in CSS).
webpack.config.js
module.exports = {
module: {
rules: [
// ...
// --------
// SCSS ALL EXCEPT MODULES
{
test: /\.scss$/i,
exclude: /\.module\.scss$/i,
use: [
{
loader: "style-loader",
},
{
loader: "css-loader",
options: {
importLoaders: 1,
modules: {
mode: "icss",
},
},
},
{
loader: "sass-loader",
},
],
},
// --------
// SCSS MODULES
{
test: /\.module\.scss$/i,
use: [
{
loader: "style-loader",
},
{
loader: "css-loader",
options: {
importLoaders: 1,
modules: {
mode: "local",
},
},
},
{
loader: "sass-loader",
},
],
},
// --------
// ...
],
},
};
variables.scss
File treated as ICSS
-only.
$colorBackground: red;
:export {
colorBackgroundCanvas: $colorBackground;
}
Component.module.scss
File treated as CSS Module
.
@import "variables.scss";
.componentClass {
background-color: $colorBackground;
}
Component.jsx
Using both CSS Module
functionality as well as SCSS variables directly in JavaScript.
import svars from "variables.scss";
import styles from "Component.module.scss";
// Render DOM with CSS modules class name
// <div className={styles.componentClass}>
// <canvas ref={mountsCanvas}/>
// </div>
// Somewhere in JavaScript canvas drawing code use the variable directly
// const ctx = mountsCanvas.current.getContext('2d',{alpha: false});
ctx.fillStyle = `${svars.colorBackgroundCanvas}`;
Please take a moment to read our contributing guidelines if you haven't yet done so.
A ESlint loader for webpack
eslint-loader
has been deprecated. Please use eslint-webpack-plugin
.
npm install eslint-loader --save-dev
Note: You also need to install eslint
from npm, if you haven't already:
npm install eslint --save-dev
In your webpack configuration:
module.exports = {
// ...
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader',
options: {
// eslint options (if necessary)
},
},
],
},
// ...
};
When using with transpiling loaders (like babel-loader
), make sure they are in correct order (bottom to top). Otherwise files will be checked after being processed by babel-loader
:
module.exports = {
// ...
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader', 'eslint-loader'],
},
],
},
// ...
};
To be safe, you can use enforce: 'pre'
section to check source files, not modified by other loaders (like babel-loader
):
module.exports = {
// ...
module: {
rules: [
{
enforce: 'pre',
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader',
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
],
},
// ...
};
You can pass eslint options using standard webpack loader options.
Note: That the config option you provide will be passed to the CLIEngine
. This is a different set of options than what you'd specify in package.json
or .eslintrc
. See the eslint docs for more detail.
cache
Boolean|String
false
This option will enable caching of the linting results into a file. This is particularly useful in reducing linting time when doing a full build.
This can either be a boolean
value or the cache directory path(ex: './.eslint-loader-cache'
).
If cache: true
is used, the cache is written to the ./node_modules/.cache/eslint-loader
directory. This is the recommended usage.
module.exports = {
entry: '...',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader',
options: {
cache: true,
},
},
],
},
};
eslintPath
String
eslint
Path to eslint
instance that will be used for linting. If the eslintPath
is a folder like a official eslint, or specify a formatter
option. Now you dont have to install eslint
.
module.exports = {
entry: '...',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader',
options: {
eslintPath: path.join(__dirname, 'reusable-eslint'),
},
},
],
},
};
fix
Boolean
false
This option will enable ESLint autofix feature.
Be careful: this option will change source files.
module.exports = {
entry: '...',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader',
options: {
fix: true,
},
},
],
},
};
formatter
String|Function
stylish
This option accepts a function that will have one argument: an array of eslint messages (object). The function must return the output as a string. You can use official eslint formatters.
module.exports = {
entry: '...',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader',
options: {
// several examples !
// default value
formatter: 'stylish',
// community formatter
formatter: require('eslint-friendly-formatter'),
// custom formatter
formatter: function (results) {
// `results` format is available here
// http://eslint.org/docs/developer-guide/nodejs-api.html#executeonfiles()
// you should return a string
// DO NOT USE console.*() directly !
return 'OUTPUT';
},
},
},
],
},
};
By default the loader will auto adjust error reporting depending on eslint errors/warnings counts. You can still force this behavior by using emitError
or emitWarning
options:
emitError
Boolean
false
Will always return errors, if this option is set to true
.
module.exports = {
entry: '...',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader',
options: {
emitError: true,
},
},
],
},
};
emitWarning
Boolean
false
Will always return warnings, if option is set to true
. If you're using hot module replacement, you may wish to enable this in development, or else updates will be skipped when there's an eslint error.
module.exports = {
entry: '...',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader',
options: {
emitWarning: true,
},
},
],
},
};
failOnError
Boolean
false
Will cause the module build to fail if there are any errors, if option is set to true
.
module.exports = {
entry: '...',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader',
options: {
failOnError: true,
},
},
],
},
};
failOnWarning
Boolean
false
Will cause the module build to fail if there are any warnings, if option is set to true
.
module.exports = {
entry: '...',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader',
options: {
failOnWarning: true,
},
},
],
},
};
quiet
Boolean
false
Will process and report errors only and ignore warnings, if this option is set to true
.
module.exports = {
entry: '...',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader',
options: {
quiet: true,
},
},
],
},
};
outputReport
Boolean|Object
false
Write the output of the errors to a file, for example a checkstyle xml file for use for reporting on Jenkins CI.
The filePath
is an absolute path or relative to the webpack config: output.path
. You can pass in a different formatter
for the output file, if none is passed in the default/configured formatter will be used.
module.exports = {
entry: '...',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader',
options: {
outputReport: {
filePath: 'checkstyle.xml',
formatter: 'checkstyle',
},
},
},
],
},
};
NoEmitOnErrorsPlugin
is now automatically enabled in webpack 4, when mode is either unset, or set to production. So even ESLint warnings will fail the build. No matter what error settings are used for eslint-loader
, except if emitWarning
enabled.
configFile
or using eslint -c path/.eslintrc
Bear in mind that when you define configFile
, eslint
doesn't automatically look for .eslintrc
files in the directory of the file to be linted. More information is available in official eslint documentation in section Using Configuration Files. See #129.
Allow to setup exports module.exports
/export
for source files.
Useful when a source file does not contain exports or something does not export.
For further hints on compatibility issues, check out Shimming of the official docs.
⚠ By default loader generate ES module named syntax.
⚠ Be careful, existing exports (
export
/module.exports
/exports
) in the original code and exporting new values can cause a failure.
To begin, you'll need to install exports-loader
:
$ npm install exports-loader --save-dev
The |
or %20
(space) allow to separate the syntax
, name
and alias
of export.
The documentation and syntax examples can be read here.
⚠
%20
is space in a query string, because you can't use spaces in URLs
Then add the loader to the desired import
statement or require
calls. For example:
import { myFunction } from "exports-loader?exports=myFunction!./file.js";
// Adds the following code to the file's source:
//
// ...
// Code
// ...
//
// export { myFunction }
myFunction("Hello world");
import {
myVariable,
myFunction,
} from "exports-loader?exports=myVariable,myFunction!./file.js";
// Adds the following code to the file's source:
//
// ...
// Code
// ...
//
// export { myVariable, myFunction };
const newVariable = myVariable + "!!!";
console.log(newVariable);
myFunction("Hello world");
const {
myFunction,
} = require("exports-loader?type=commonjs&exports=myFunction!./file.js");
// Adds the following code to the file's source:
//
// ...
// Code
// ...
//
// module.exports = { myFunction }
myFunction("Hello world");
// Alternative syntax:
// import myFunction from 'exports-loader?exports=default%20myFunction!./file.js';
import myFunction from "exports-loader?exports=default|myFunction!./file.js";
// `%20` is space in a query string, equivalently `default myFunction`
// Adds the following code to the file's source:
//
// ...
// Code
// ...
//
// exports default myFunction;
myFunction("Hello world");
const myFunction = require("exports-loader?type=commonjs&exports=single|myFunction!./file.js");
// `|` is separator in a query string, equivalently `single|myFunction`
// Adds the following code to the file's source:
//
// ...
// Code
// ...
//
// module.exports = myFunction;
myFunction("Hello world");
import { myFunctionAlias } from "exports-loader?exports=named|myFunction|myFunctionAlias!./file.js";
// `|` is separator in a query string, equivalently `named|myFunction|myFunctionAlias`
// Adds the following code to the file's source:
//
// ...
// Code
// ...
//
// exports { myFunction as myFunctionAlias };
myFunctionAlias("Hello world");
Description of string values can be found in the documentation below.
webpack.config.js
module.exports = {
module: {
rules: [
{
// You can use `regexp`
// test: /vendor\.js/$
test: require.resolve("./path/to/vendor.js"),
loader: "exports-loader",
options: {
exports: "myFunction",
},
},
],
},
};
And run webpack
via your preferred method.
Name | Type | Default | Description |
---|---|---|---|
Name Type Default Description
|
{String} |
module |
Format of generated exports |
Name Type Default Description
|
{String\|Object\|Array<String\|Object>} |
undefined |
List of exports |
type
Type: String
Default: module
Format of generated exports.
Possible values - commonjs
(CommonJS module syntax) and module
(ES module syntax).
commonjs
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("./path/to/vendor.js"),
loader: "exports-loader",
options: {
type: "commonjs",
exports: "Foo",
},
},
],
},
};
Generate output:
// ...
// Code
// ...
module.exports = { Foo };
module
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("./path/to/vendor.js"),
loader: "exports-loader",
options: {
type: "module",
exports: "Foo",
},
},
],
},
};
Generate output:
// ...
// Code
// ...
export { Foo };
exports
Type: String|Array
Default: undefined
List of exports.
String
Allows to use a string to describe an export.
Syntax
The |
or %20
(space) allow to separate the syntax
, name
and alias
of export.
String syntax - [[syntax] [name] [alias]]
or [[syntax]|[name]|[alias]]
, where:
[syntax]
(may be omitted) -
type
is module
- can be default
and named
,type
is commonjs
- can be single
and multiple
[name]
- name of an exported value (required)
[alias]
- alias of an exported value (may be omitted)
Examples:
[Foo]
- generates export { Foo };
.[default Foo]
- generates export default Foo;
.[named Foo]
- generates export { Foo };
.[named Foo FooA]
- generates export { Foo as FooA };
.[single Foo]
- generates module.exports = Foo;
.[multiple Foo]
- generates module.exports = { Foo };
.[multiple Foo FooA]
- generates module.exports = { 'FooA': Foo };
.[named [name] [name]Alias]
- generates ES module named exports and exports a value equal to the filename under other name., for single.js
it will be single
and singleAlias
, generates export { single as singleAlias };
.⚠ You need to set
type: "commonjs"
to usesingle
ormultiple
syntaxes.⚠ Aliases can't be used together with
default
orsingle
syntaxes.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("./path/to/vendor.js"),
loader: "exports-loader",
options: {
exports: "default Foo",
},
},
],
},
};
Generate output:
// ...
// Code
// ...
export default Foo;
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("./path/to/vendor.js"),
loader: "exports-loader",
options: {
exports: "named Foo FooA",
},
},
],
},
};
Generate output:
// ...
// Code
// ...
export { Foo as FooA };
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("./path/to/vendor.js"),
loader: "exports-loader",
options: {
type: "commonjs",
exports: "single Foo",
},
},
],
},
};
Generate output:
// ...
// Code
// ...
module.exports = Foo;
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("./path/to/vendor.js"),
loader: "exports-loader",
options: {
type: "commonjs",
exports: "multiple Foo FooA",
},
},
],
},
};
Generate output:
// ...
// Code
// ...
module.exports = { FooA: Foo };
Object
Allows to use an object to describe an export.
Properties:
syntax
- can be default
or named
for the module
type (ES modules
module format), and single
or multiple
for the commonjs
type (CommonJS
module format) (may be omitted)name
- name of an exported value (required)alias
- alias of an exported value (may be omitted)webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("./path/to/vendor.js"),
loader: "exports-loader",
options: {
exports: {
syntax: "default",
name: "Foo",
},
},
},
],
},
};
Generate output:
// ...
// Code
// ...
export default Foo;
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("./path/to/vendor.js"),
loader: "exports-loader",
options: {
exports: {
syntax: "named",
name: "Foo",
alias: "FooA",
},
},
},
],
},
};
Generate output:
// ...
// Code
// ...
export { Foo as FooA };
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("./path/to/vendor.js"),
loader: "exports-loader",
options: {
type: "commonjs",
exports: {
syntax: "single",
name: "Foo",
},
},
},
],
},
};
Generate output:
// ...
// Code
// ...
module.exports = Foo;
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("./path/to/vendor.js"),
loader: "exports-loader",
options: {
type: "commonjs",
exports: {
syntax: "multiple",
name: "Foo",
alias: "FooA",
},
},
},
],
},
};
Generate output:
// ...
// Code
// ...
module.exports = { FooA: Foo };
Array
Allow to specify multiple exports. Each item can be a string
or an object
.
⚠ Not possible to use
single
andmultiple
syntaxes together due to CommonJS format limitations.⚠ Not possible to use multiple
default
values due to ES module format limitations.⚠ Not possible to use multiple
single
values due to CommonJS format limitations.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("./path/to/vendor.js"),
loader: "exports-loader",
options: {
type: "commonjs",
exports: ["Foo", "multiple Bar", "multiple Baz BazA"],
},
},
],
},
};
Generate output:
// ...
// Code
// ...
module.exports = { Foo, Bar, BazA: Bar };
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("./path/to/vendor.js"),
loader: "exports-loader",
options: {
exports: ["default Foo", "named Bar BarA"],
},
},
],
},
};
Generate output:
// ...
// Code
// ...
export default Foo;
export { Bar as BarA };
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("./path/to/vendor.js"),
loader: "exports-loader",
options: {
exports: [
{ syntax: "named", name: "Foo", alias: "FooA" },
{ syntax: "named", name: "Bar" },
"Baz",
],
},
},
],
},
};
Generate output:
// ...
// Code
// ...
export { Foo as FooA, Bar, Baz };
Please take a moment to read our contributing guidelines if you haven't yet done so.
The expose-loader
loader allows to expose a module (in whole or in part) to global object (self
, window
and global
).
For further hints on compatibility issues, check out Shimming of the official docs.
To begin, you'll need to install expose-loader
:
$ npm install expose-loader --save-dev
(If you're using WebPack 4, install expose-loader@1
and follow the corresponding instructions instead.)
Then you can use the expose-loader
using two approaches.
The |
or %20
(space) allow to separate the globalName
, moduleLocalName
and override
of expose.
The documentation and syntax examples can be read here.
⚠
%20
is space in a query string, because you can't use spaces in URLs
import $ from "expose-loader?exposes=$,jQuery!jquery";
//
// Adds the `jquery` to the global object under the names `$` and `jQuery`
import { concat } from "expose-loader?exposes=_.concat!lodash/concat";
//
// Adds the `lodash/concat` to the global object under the name `_.concat`
import {
map,
reduce,
} from "expose-loader?exposes=_.map|map,_.reduce|reduce!underscore";
//
// Adds the `map` and `reduce` method from `underscore` to the global object under the name `_.map` and `_.reduce`
src/index.js
import $ from "jquery";
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("jquery"),
loader: "expose-loader",
options: {
exposes: ["$", "jQuery"],
},
},
{
test: require.resolve("underscore"),
loader: "expose-loader",
options: {
exposes: [
"_.map|map",
{
globalName: "_.reduce",
moduleLocalName: "reduce",
},
{
globalName: ["_", "filter"],
moduleLocalName: "filter",
},
],
},
},
],
},
};
The require.resolve
call is a Node.js function (unrelated to require.resolve
in webpack processing).
require.resolve
gives you the absolute path to the module ("/.../app/node_modules/jquery/dist/jquery.js"
).
So the expose only applies to the jquery
module. And it's only exposed when used in the bundle.
And run webpack
via your preferred method.
Name | Type | Default | Description |
---|---|---|---|
Name Type Default Description
|
{String\|Object\|Array<String\|Object>} |
undefined |
List of exposes |
exposes
Type: String|Object|Array<String|Object>
Default: undefined
List of exposes.
String
Allows to use a string to describe an expose.
Syntax
The |
or %20
(space) allow to separate the globalName
, moduleLocalName
and override
of expose.
String syntax - [[globalName] [moduleLocalName] [override]]
or [[globalName]|[moduleLocalName]|[override]]
, where:
globalName
- the name in the global object, for example window.$
for a browser environment (required)moduleLocalName
- the name of method/variable/etc of the module (the module must export it) (may be omitted)override
- allows to override existing value in the global object (may be omitted)If moduleLocalName
is not specified, it exposes the entire module to the global object, otherwise it exposes only the value of moduleLocalName
.
src/index.js
import _ from "underscore";
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("jquery"),
loader: "expose-loader",
options: {
// For `underscore` library, it can be `_.map map` or `_.map|map`
exposes: "jquery",
},
},
],
},
};
Object
Allows to use an object to describe an expose.
globalName
Type: String|Array<String>
Default: undefined
The name in the global object. (required).
src/index.js
import _ from "underscore";
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("underscore"),
loader: "expose-loader",
options: {
exposes: {
// Can be `['_', 'filter']`
globalName: "_.filter",
moduleLocalName: "filter",
},
},
},
],
},
};
moduleLocalName
Type: String
Default: undefined
The name of method/variable/etc of the module (the module must export it).
If moduleLocalName
is specified, it exposes only the value of moduleLocalName
.
src/index.js
import _ from "underscore";
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("underscore"),
loader: "expose-loader",
options: {
exposes: {
globalName: "_.filter",
moduleLocalName: "filter",
},
},
},
],
},
};
override
Type: Boolean
Default: false
By default loader does not override the existing value in the global object, because it is unsafe.
In development
mode, we throw an error if the value already present in the global object.
But you can configure loader to override the existing value in the global object using this option.
To force override the value that is already present in the global object you can set the override
option to the true
value.
src/index.js
import $ from "jquery";
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("jquery"),
loader: "expose-loader",
options: {
exposes: {
globalName: "$",
override: true,
},
},
},
],
},
};
Array
src/index.js
import _ from "underscore";
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("underscore"),
loader: "expose-loader",
options: {
exposes: [
"_.map map",
{
globalName: "_.filter",
moduleLocalName: "filter",
},
{
globalName: ["_", "find"],
moduleLocalName: "myNameForFind",
},
],
},
},
],
},
};
It will expose only map
, filter
and find
(under myNameForFind
name) methods to the global object.
In a browser these methods will be available under windows._.map(..args)
, windows._.filter(...args)
and windows._.myNameForFind(...args)
methods.
Please take a moment to read our contributing guidelines if you haven't yet done so.
webpack loader to extract HTML and CSS from the bundle.
The extract-loader evaluates the given source code on the fly and returns the result as string. Its main use-case is to resolve urls within HTML and CSS coming from their respective loaders. Use the file-loader to emit the extract-loader's result as separate file.
import stylesheetUrl from "file-loader!extract-loader!css-loader!main.css";
// stylesheetUrl will now be the hashed url to the final stylesheet
The extract-loader works similar to the extract-text-webpack-plugin and the mini-css-extract-plugin and is meant as a lean alternative to it. When evaluating the source code, it provides a fake context which was especially designed to cope with the code generated by the html- or the css-loader. Thus it might not work in other situations.
$ npm install extract-loader --save-dev
Bundling CSS with webpack has some nice advantages like referencing images and fonts with hashed urls or hot module replacement in development. In production, on the other hand, it's not a good idea to apply your stylesheets depending on JS execution. Rendering may be delayed or even a FOUC might be visible. Thus it's still better to have them as separate files in your final production build.
With the extract-loader, you are able to reference your main.css
as regular entry
. The following webpack.config.js
shows how to load your styles with the style-loader in development and as separate file in production.
module.exports = ({ mode }) => {
const pathToMainCss = require.resolve("./app/main.css");
const loaders = [{
loader: "css-loader",
options: {
sourceMap: true
}
}];
if (mode === "production") {
loaders.unshift(
"file-loader",
"extract-loader"
);
} else {
loaders.unshift("style-loader");
}
return {
mode,
entry: pathToMainCss,
module: {
rules: [
{
test: pathToMainCss,
loaders: loaders
},
]
}
};
};
You can even add your index.html
as entry
and reference your stylesheets from there. In that case, tell the html-loader to also pick up link:href
:
module.exports = ({ mode }) => {
const pathToMainJs = require.resolve("./app/main.js");
const pathToIndexHtml = require.resolve("./app/index.html");
return {
mode,
entry: [
pathToMainJs,
pathToIndexHtml
],
module: {
rules: [
{
test: pathToIndexHtml,
use: [
"file-loader",
"extract-loader",
{
loader: "html-loader",
options: {
attrs: ["img:src", "link:href"]
}
}
]
},
{
test: /\.css$/,
use: [
"file-loader",
"extract-loader",
{
loader: "css-loader",
options: {
sourceMap: true
}
}
]
},
{
test: /\.jpg$/,
use: "file-loader"
}
]
}
};
}
turns
<html>
<head>
<link href="main.css" type="text/css" rel="stylesheet">
</head>
<body>
<img src="hi.jpg">
</body>
</html>
into
<html>
<head>
<link href="7c57758b88216530ef48069c2a4c685a.css" type="text/css" rel="stylesheet">
</head>
<body>
<img src="6ac05174ae9b62257ff3aa8be43cf828.jpg">
</body>
</html>
If you want source maps in your extracted CSS files, you need to set the sourceMap
option of the css-loader:
{
loader: "css-loader",
options: {
sourceMap: true
}
}
There is currently exactly one option: publicPath
.
If you are using a relative publicPath
in webpack's output options and extracting to a file with the file-loader
, you might need this to account for the location of your extracted file. publicPath
may be defined as a string or a function that accepts current loader context as single argument.
Example with publicPath option as a string:
module.exports = {
output: {
path: path.resolve("./dist"),
publicPath: "dist/"
},
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: "file-loader",
options: {
name: "assets/[name].[ext]",
},
},
{
loader: "extract-loader",
options: {
publicPath: "../",
}
},
{
loader: "css-loader",
},
],
}
]
}
};
Example with publicPath option as a function:
module.exports = {
output: {
path: path.resolve("./dist"),
publicPath: "dist/"
},
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: "file-loader",
options: {
name: "assets/[name].[ext]",
},
},
{
loader: "extract-loader",
options: {
// dynamically return a relative publicPath based on how deep in directory structure the loaded file is in /src/ directory
publicPath: (context) => '../'.repeat(path.relative(path.resolve('src'), context.context).split('/').length),
}
},
{
loader: "css-loader",
},
],
}
]
}
};
You need another option? Then you should think about:
From opening a bug report to creating a pull request: every contribution is appreciated and welcome. If you're planning to implement a new feature or change the api please create an issue first. This way we can ensure that your precious work is not in vain.
All pull requests should have 100% test coverage (with notable exceptions) and need to pass all tests.
npm test
to run the unit testsnpm run coverage
to check the test coverage (using istanbul)Unlicense
DEPRECATED for v5: please consider migrating to asset modules
.
The file-loader
resolves import
/require()
on a file into a url and emits the file into the output directory.
To begin, you'll need to install file-loader
:
$ npm install file-loader --save-dev
Import (or require
) the target file(s) in one of the bundle's files:
file.js
import img from './file.png';
Then add the loader to your webpack
config. For example:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: 'file-loader',
},
],
},
],
},
};
And run webpack
via your preferred method. This will emit file.png
as a file
in the output directory (with the specified naming convention, if options are
specified to do so) and returns the public URI of the file.
ℹ️ By default the filename of the resulting file is the hash of the file's contents with the original extension of the required resource.
name
Type: String|Function
Default: '[contenthash].[ext]'
Specifies a custom filename template for the target file(s) using the query
parameter name
. For example, to emit a file from your context
directory into
the output directory retaining the full directory structure, you might use:
String
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(png|jpe?g|gif)$/i,
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
},
},
],
},
};
Function
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(png|jpe?g|gif)$/i,
loader: 'file-loader',
options: {
name(resourcePath, resourceQuery) {
// `resourcePath` - `/absolute/path/to/file.js`
// `resourceQuery` - `?foo=bar`
if (process.env.NODE_ENV === 'development') {
return '[path][name].[ext]';
}
return '[contenthash].[ext]';
},
},
},
],
},
};
ℹ️ By default the path and name you specify will output the file in that same directory, and will also use the same URI path to access the file.
outputPath
Type: String|Function
Default: undefined
Specify a filesystem path where the target file(s) will be placed.
String
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(png|jpe?g|gif)$/i,
loader: 'file-loader',
options: {
outputPath: 'images',
},
},
],
},
};
Function
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(png|jpe?g|gif)$/i,
loader: 'file-loader',
options: {
outputPath: (url, resourcePath, context) => {
// `resourcePath` is original absolute path to asset
// `context` is directory where stored asset (`rootContext`) or `context` option
// To get relative path you can use
// const relativePath = path.relative(context, resourcePath);
if (/my-custom-image\.png/.test(resourcePath)) {
return `other_output_path/${url}`;
}
if (/images/.test(context)) {
return `image_output_path/${url}`;
}
return `output_path/${url}`;
},
},
},
],
},
};
publicPath
Type: String|Function
Default: __webpack_public_path__
+outputPath
Specifies a custom public path for the target file(s).
String
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(png|jpe?g|gif)$/i,
loader: 'file-loader',
options: {
publicPath: 'assets',
},
},
],
},
};
Function
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(png|jpe?g|gif)$/i,
loader: 'file-loader',
options: {
publicPath: (url, resourcePath, context) => {
// `resourcePath` is original absolute path to asset
// `context` is directory where stored asset (`rootContext`) or `context` option
// To get relative path you can use
// const relativePath = path.relative(context, resourcePath);
if (/my-custom-image\.png/.test(resourcePath)) {
return `other_public_path/${url}`;
}
if (/images/.test(context)) {
return `image_output_path/${url}`;
}
return `public_path/${url}`;
},
},
},
],
},
};
postTransformPublicPath
Type: Function
Default: undefined
Specifies a custom function to post-process the generated public path. This can be used to prepend or append dynamic global variables that are only available at runtime, like __webpack_public_path__
. This would not be possible with just publicPath
, since it stringifies the values.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(png|jpg|gif)$/i,
loader: 'file-loader',
options: {
publicPath: '/some/path/',
postTransformPublicPath: (p) => `__webpack_public_path__ + ${p}`,
},
},
],
},
};
context
Type: String
Default: context
Specifies a custom file context.
module.exports = {
module: {
rules: [
{
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: 'file-loader',
options: {
context: 'project',
},
},
],
},
],
},
};
emitFile
Type: Boolean
Default: true
If true, emits a file (writes a file to the filesystem). If false, the loader will return a public URI but will not emit the file. It is often useful to disable this option for server-side packages.
file.js
// bundle file
import img from './file.png';
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
{
loader: 'file-loader',
options: {
emitFile: false,
},
},
],
},
],
},
};
regExp
Type: RegExp
Default: undefined
Specifies a Regular Expression to one or many parts of the target file path.
The capture groups can be reused in the name
property using [N]
placeholder.
file.js
import img from './customer01/file.png';
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: 'file-loader',
options: {
regExp: /\/([a-z0-9]+)\/[a-z0-9]+\.png$/i,
name: '[1]-[name].[ext]',
},
},
],
},
],
},
};
ℹ️ If
[0]
is used, it will be replaced by the entire tested string, whereas[1]
will contain the first capturing parenthesis of your regex and so on...
esModule
Type: Boolean
Default: true
By default, file-loader
generates JS modules that use the ES modules syntax.
There are some cases in which using ES modules is beneficial, like in the case of module concatenation and tree shaking.
You can enable a CommonJS module syntax using:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: 'file-loader',
options: {
esModule: false,
},
},
],
},
],
},
};
Full information about placeholders you can find here.
[ext]
Type: String
Default: file.extname
The file extension of the target file/resource.
[name]
Type: String
Default: file.basename
The basename of the file/resource.
[path]
Type: String
Default: file.directory
The path of the resource relative to the webpack/config context
.
[folder]
Type: String
Default: file.folder
The folder of the resource is in.
[query]
Type: String
Default: file.query
The query of the resource, i.e. ?foo=bar
.
[emoji]
Type: String
Default: undefined
A random emoji representation of content
.
[emoji:<length>]
Type: String
Default: undefined
Same as above, but with a customizable number of emojis
[hash]
Type: String
Default: md4
Specifies the hash method to use for hashing the file content.
[contenthash]
Type: String
Default: md4
Specifies the hash method to use for hashing the file content.
[<hashType>:hash:<digestType>:<length>]
Type: String
The hash of options.content (Buffer) (by default it's the hex digest of the hash).
digestType
Type: String
Default: 'hex'
The digest that the hash function should use. Valid values include: base26, base32, base36, base49, base52, base58, base62, base64, and hex.
hashType
Type: String
Default: 'md4'
The type of hash that the hash function should use. Valid values include: md4
, md5
, sha1
, sha256
, and sha512
.
length
Type: Number
Default: undefined
Users may also specify a length for the computed hash.
[N]
Type: String
Default: undefined
The n-th match obtained from matching the current file name against the regExp
.
The following examples show how one might use file-loader
and what the result would be.
file.js
import png from './image.png';
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: 'file-loader',
options: {
name: 'dirname/[contenthash].[ext]',
},
},
],
},
],
},
};
Result:
# result
dirname/0dcbbaa701328ae351f.png
file.js
import png from './image.png';
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: 'file-loader',
options: {
name: '[sha512:hash:base64:7].[ext]',
},
},
],
},
],
},
};
Result:
# result
gdyb21L.png
file.js
import png from './path/to/file.png';
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: 'file-loader',
options: {
name: '[path][name].[ext]?[contenthash]',
},
},
],
},
],
},
};
Result:
# result
path/to/file.png?e43b20c069c4a01867c31e98cbce33c9
The following examples show how to use file-loader
for CDN uses query params.
file.js
import png from './directory/image.png?width=300&height=300';
webpack.config.js
module.exports = {
output: {
publicPath: 'https://cdn.example.com/',
},
module: {
rules: [
{
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: 'file-loader',
options: {
name: '[path][name].[ext][query]',
},
},
],
},
],
},
};
Result:
# result
https://cdn.example.com/directory/image.png?width=300&height=300
An application might want to configure different CDN hosts depending on an environment variable that is only available when running the application. This can be an advantage, as only one build of the application is necessary, which behaves differently depending on environment variables of the deployment environment. Since file-loader is applied when compiling the application, and not when running it, the environment variable cannot be used in the file-loader configuration. A way around this is setting the __webpack_public_path__
to the desired CDN host depending on the environment variable at the entrypoint of the application. The option postTransformPublicPath
can be used to configure a custom path depending on a variable like __webpack_public_path__
.
main.js
const assetPrefixForNamespace = (namespace) => {
switch (namespace) {
case 'prod':
return 'https://cache.myserver.net/web';
case 'uat':
return 'https://cache-uat.myserver.net/web';
case 'st':
return 'https://cache-st.myserver.net/web';
case 'dev':
return 'https://cache-dev.myserver.net/web';
default:
return '';
}
};
const namespace = process.env.NAMESPACE;
__webpack_public_path__ = `${assetPrefixForNamespace(namespace)}/`;
file.js
import png from './image.png';
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(png|jpg|gif)$/i,
loader: 'file-loader',
options: {
name: '[name].[contenthash].[ext]',
outputPath: 'static/assets/',
publicPath: 'static/assets/',
postTransformPublicPath: (p) => `__webpack_public_path__ + ${p}`,
},
},
],
},
};
Result when run with NAMESPACE=prod
env variable:
# result
https://cache.myserver.net/web/static/assets/image.somehash.png
Result when run with NAMESPACE=dev
env variable:
# result
https://cache-dev.myserver.net/web/static/assets/image.somehash.png
Please take a moment to read our contributing guidelines if you haven't yet done so.
gzip loader module for webpack
Enables loading gzipped resources.
npm install --save-dev gzip-loader
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.gz$/,
enforce: 'pre',
use: 'gzip-loader'
}
]
}
}
bundle.js
require("gzip-loader!./file.js.gz");
John-David Dalton | Juho Vepsäläinen | Joshua Wiens | Michael Ciniawsky | Alexander Krasnoyarov |
Exports HTML as string. HTML is minimized when the compiler demands.
To begin, you'll need to install html-loader
:
npm install --save-dev html-loader
Then add the plugin to your webpack
config. For example:
file.js
import html from "./file.html";
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader",
},
],
},
};
Name | Type | Default | Description |
---|---|---|---|
Name Type Default Description
|
{Boolean\|Object} |
true |
Enables/Disables sources handling |
Name Type Default Description
|
{Function} |
undefined |
Allows pre-processing of content before handling |
Name Type Default Description
|
{Boolean\|Object} |
true
in production mode, otherwise
false |
Tell
html-loader
to minimize HTML |
Name Type Default Description
|
{Boolean} |
true |
Enable/disable ES modules syntax |
sources
Type: Boolean|Object
Default: true
By default every loadable attributes (for example - <img src="image.png">
) is imported (const img = require('./image.png')
or import img from "./image.png""
).
You may need to specify loaders for images in your configuration (recommended asset modules
).
Supported tags and attributes:
src
attribute of the audio
tagsrc
attribute of the embed
tagsrc
attribute of the img
tagsrcset
attribute of the img
tagsrc
attribute of the input
tagdata
attribute of the object
tagsrc
attribute of the script
taghref
attribute of the script
tagxlink:href
attribute of the script
tagsrc
attribute of the source
tagsrcset
attribute of the source
tagsrc
attribute of the track
tagposter
attribute of the video
tagsrc
attribute of the video
tagxlink:href
attribute of the image
taghref
attribute of the image
tagxlink:href
attribute of the use
taghref
attribute of the use
taghref
attribute of the link
tag when the rel
attribute contains stylesheet
, icon
, shortcut icon
, mask-icon
, apple-touch-icon
, apple-touch-icon-precomposed
, apple-touch-startup-image
, manifest
, prefetch
, preload
or when the itemprop
attribute is image
, logo
, screenshot
, thumbnailurl
, contenturl
, downloadurl
, duringmedia
, embedurl
, installurl
, layoutimage
imagesrcset
attribute of the link
tag when the rel
attribute contains stylesheet
, icon
, shortcut icon
, mask-icon
, apple-touch-icon
, apple-touch-icon-precomposed
, apple-touch-startup-image
, manifest
, prefetch
, preload
content
attribute of the meta
tag when the name
attribute is msapplication-tileimage
, msapplication-square70x70logo
, msapplication-square150x150logo
, msapplication-wide310x150logo
, msapplication-square310x310logo
, msapplication-config
, twitter:image
or when the property
attribute is og:image
, og:image:url
, og:image:secure_url
, og:audio
, og:audio:secure_url
, og:video
, og:video:secure_url
, vk:image
or when the itemprop
attribute is image
, logo
, screenshot
, thumbnailurl
, contenturl
, downloadurl
, duringmedia
, embedurl
, installurl
, layoutimage
icon-uri
value component in content
attribute of the meta
tag when the name
attribute is msapplication-task
Boolean
The true
value enables processing of all default elements and attributes, the false
disable processing of all attributes.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader",
options: {
// Disables attributes processing
sources: false,
},
},
],
},
};
Object
Allows you to specify which tags and attributes to process, filter them, filter urls and process sources starts with /
.
For example:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader",
options: {
sources: {
list: [
// All default supported tags and attributes
"...",
{
tag: "img",
attribute: "data-src",
type: "src",
},
{
tag: "img",
attribute: "data-srcset",
type: "srcset",
},
],
urlFilter: (attribute, value, resourcePath) => {
// The `attribute` argument contains a name of the HTML attribute.
// The `value` argument contains a value of the HTML attribute.
// The `resourcePath` argument contains a path to the loaded HTML file.
if (/example\.pdf$/.test(value)) {
return false;
}
return true;
},
},
},
},
],
},
};
list
Type: Array
Default: supported tags and attributes.
Allows to setup which tags and attributes to process and how, and the ability to filter some of them.
Using ...
syntax allows you to extend default supported tags and attributes.
For example:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader",
options: {
sources: {
list: [
// All default supported tags and attributes
"...",
{
tag: "img",
attribute: "data-src",
type: "src",
},
{
tag: "img",
attribute: "data-srcset",
type: "srcset",
},
{
// Tag name
tag: "link",
// Attribute name
attribute: "href",
// Type of processing, can be `src` or `scrset`
type: "src",
// Allow to filter some attributes
filter: (tag, attribute, attributes, resourcePath) => {
// The `tag` argument contains a name of the HTML tag.
// The `attribute` argument contains a name of the HTML attribute.
// The `attributes` argument contains all attributes of the tag.
// The `resourcePath` argument contains a path to the loaded HTML file.
if (/my-html\.html$/.test(resourcePath)) {
return false;
}
if (!/stylesheet/i.test(attributes.rel)) {
return false;
}
if (
attributes.type &&
attributes.type.trim().toLowerCase() !== "text/css"
) {
return false;
}
return true;
},
},
],
},
},
},
],
},
};
If the tag name is not specified it will process all the tags.
You can use your custom filter to specify html elements to be processed.
For example:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader",
options: {
sources: {
list: [
{
// Attribute name
attribute: "src",
// Type of processing, can be `src` or `scrset`
type: "src",
// Allow to filter some attributes (optional)
filter: (tag, attribute, attributes, resourcePath) => {
// The `tag` argument contains a name of the HTML tag.
// The `attribute` argument contains a name of the HTML attribute.
// The `attributes` argument contains all attributes of the tag.
// The `resourcePath` argument contains a path to the loaded HTML file.
// choose all HTML tags except img tag
return tag.toLowerCase() !== "img";
},
},
],
},
},
},
],
},
};
Filter can also be used to extend the supported elements and attributes.
For example, filter can help process meta tags that reference assets:
module.exports = {
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader",
options: {
sources: {
list: [
{
tag: "meta",
attribute: "content",
type: "src",
filter: (tag, attribute, attributes, resourcePath) => {
if (
attributes.value === "og:image" ||
attributes.name === "twitter:image"
) {
return true;
}
return false;
},
},
],
},
},
},
],
},
};
Note: source with a tag
option takes precedence over source without.
Filter can be used to disable default sources.
For example:
module.exports = {
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader",
options: {
sources: {
list: [
"...",
{
tag: "img",
attribute: "src",
type: "src",
filter: () => false,
},
],
},
},
},
],
},
};
urlFilter
Type: Function
Default: undefined
Allow to filter urls. All filtered urls will not be resolved (left in the code as they were written).
All non requestable sources (for example <img src="javascript:void(0)">
) do not handle by default.
module.exports = {
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader",
options: {
sources: {
urlFilter: (attribute, value, resourcePath) => {
// The `attribute` argument contains a name of the HTML attribute.
// The `value` argument contains a value of the HTML attribute.
// The `resourcePath` argument contains a path to the loaded HTML file.
if (/example\.pdf$/.test(value)) {
return false;
}
return true;
},
},
},
},
],
},
};
preprocessor
Type: Function
Default: undefined
Allows pre-processing of content before handling.
⚠ You should always return valid HTML
file.hbs
<div>
<p>{{firstname}} {{lastname}}</p>
<img src="image.png" alt="alt" />
<div>
Function
You can set the preprocessor
option as a Function
instance.
webpack.config.js
const Handlebars = require("handlebars");
module.exports = {
module: {
rules: [
{
test: /\.hbs$/i,
loader: "html-loader",
options: {
preprocessor: (content, loaderContext) => {
let result;
try {
result = Handlebars.compile(content)({
firstname: "Value",
lastname: "OtherValue",
});
} catch (error) {
loaderContext.emitError(error);
return content;
}
return result;
},
},
},
],
},
};
You can also set the preprocessor
option as an asynchronous function instance.
For example:
webpack.config.js
const Handlebars = require("handlebars");
module.exports = {
module: {
rules: [
{
test: /\.hbs$/i,
loader: "html-loader",
options: {
preprocessor: async (content, loaderContext) => {
let result;
try {
result = await Handlebars.compile(content)({
firstname: "Value",
lastname: "OtherValue",
});
} catch (error) {
await loaderContext.emitError(error);
return content;
}
return result;
},
},
},
],
},
};
minimize
Type: Boolean|Object
Default: true
in production mode, otherwise false
Tell html-loader
to minimize HTML.
Boolean
The enabled rules for minimizing by default are the following ones:
({
caseSensitive: true,
collapseWhitespace: true,
conservativeCollapse: true,
keepClosingSlash: true,
minifyCSS: true,
minifyJS: true,
removeComments: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
});
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader",
options: {
minimize: true,
},
},
],
},
};
Object
webpack.config.js
See html-minifier-terser's documentation for more information on the available options.
The rules can be disabled using the following options in your webpack.conf.js
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader",
options: {
minimize: {
removeComments: false,
collapseWhitespace: false,
},
},
},
],
},
};
esModule
Type: Boolean
Default: true
By default, html-loader
generates JS modules that use the ES modules syntax.
There are some cases in which using ES modules is beneficial, like in the case of module concatenation and tree shaking.
You can enable a CommonJS modules syntax using:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader",
options: {
esModule: false,
},
},
],
},
};
commentWith comment, can to disable sources handling for next tag.
<img src="image.png" />
<img
srcset="image.png 480w, image.png 768w"
src="image.png"
alt="Elva dressed as a fairy"
/>
<meta itemprop="image" content="./image.png" />
<link rel="icon" type="image/png" sizes="192x192" href="./image.png" />
With resolve.roots
can specify a list of directories where requests of server-relative URLs (starting with '/') are resolved.
webpack.config.js
module.exports = {
context: __dirname,
module: {
rules: [
{
test: /\.html$/i,
loader: "html-loader",
options: {},
},
{
test: /\.jpg$/,
type: "asset/resource",
},
],
},
resolve: {
roots: [path.resolve(__dirname, "fixtures")],
},
};
file.html
<img src="/image.jpg" />
// => image.jpg in __dirname/fixtures will be resolved
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.jpg$/,
type: "asset/resource",
},
{
test: /\.png$/,
type: "asset/inline",
},
],
},
output: {
publicPath: "http://cdn.example.com/[fullhash]/",
},
};
file.html
<img src="image.jpg" data-src="image2x.png" />
index.js
require("html-loader!./file.html");
// => '<img src="http://cdn.example.com/49eba9f/a992ca.jpg" data-src="image2x.png">'
require('html-loader?{"sources":{"list":[{"tag":"img","attribute":"data-src","type":"src"}]}}!./file.html');
// => '<img src="image.jpg" data-src="data:image/png;base64,..." >'
require('html-loader?{"sources":{"list":[{"tag":"img","attribute":"src","type":"src"},{"tag":"img","attribute":"data-src","type":"src"}]}}!./file.html');
// => '<img src="http://cdn.example.com/49eba9f/a992ca.jpg" data-src="data:image/png;base64,..." >'
script
and link
tagsscript.file.js
console.log(document);
style.file.css
a {
color: red;
}
file.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Title of the document</title>
<link rel="stylesheet" type="text/css" href="./style.file.css" />
</head>
<body>
Content of the document......
<script src="./script.file.js"></script>
</body>
</html>
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.html$/,
type: "asset/resource",
generator: {
filename: "[name][ext]",
},
},
{
test: /\.html$/i,
use: ["extract-loader", "html-loader"],
},
{
test: /\.js$/i,
exclude: /\.file.js$/i,
loader: "babel-loader",
},
{
test: /\.file.js$/i,
type: "asset/resource",
},
{
test: /\.css$/i,
exclude: /\.file.css$/i,
loader: "css-loader",
},
{
test: /\.file.css$/i,
type: "asset/resource",
},
],
},
};
You can use any template system. Below is an example for handlebars.
file.hbs
<div>
<p>{{firstname}} {{lastname}}</p>
<img src="image.png" alt="alt" />
<div>
webpack.config.js
const Handlebars = require("handlebars");
module.exports = {
module: {
rules: [
{
test: /\.hbs$/i,
loader: "html-loader",
options: {
preprocessor: (content, loaderContext) => {
let result;
try {
result = Handlebars.compile(content)({
firstname: "Value",
lastname: "OtherValue",
});
} catch (error) {
loaderContext.emitError(error);
return content;
}
return result;
},
},
},
],
},
};
You can use PostHTML without any additional loaders.
file.html
<img src="image.jpg" />
webpack.config.js
const posthtml = require("posthtml");
const posthtmlWebp = require("posthtml-webp");
module.exports = {
module: {
rules: [
{
test: /\.hbs$/i,
loader: "html-loader",
options: {
preprocessor: (content, loaderContext) => {
let result;
try {
result = posthtml().use(plugin).process(content, { sync: true });
} catch (error) {
loaderContext.emitError(error);
return content;
}
return result.html;
},
},
},
],
},
};
A very common scenario is exporting the HTML into their own .html file, to serve them directly instead of injecting with javascript. This can be achieved with a combination of 2 loaders:
and asset modules
The html-loader will parse the URLs, require the images and everything you
expect. The extract loader will parse the javascript back into a proper html
file, ensuring images are required and point to proper path, and the asset modules
will write the .html file for you. Example:
webpack.config.js
module.exports = {
output: {
assetModuleFilename: "[name][ext]",
},
module: {
rules: [
{
test: /\.html$/,
type: "asset/resource",
generator: {
filename: "[name][ext]",
},
},
{
test: /\.html$/i,
use: ["extract-loader", "html-loader"],
},
],
},
};
Please take a moment to read our contributing guidelines if you haven't yet done so.
{
"red": "red",
"green": "green",
"blue": "blue"
}
{
"red": "rot",
"green": "gr�n"
}
// assuming our locale is "de-de-berlin"
var locale = require("i18n!./colors.json");
// wait for ready, this is only required once for all locales in a web app
// because all locales of the same language are merged into one chuck
locale(function() {
console.log(locale.red); // prints rot
console.log(locale.blue); // prints blue
});
You should tell the loader about all your locales, if you want to load them once and than want to use them synchronous.
{
"i18n": {
"locales": [
"de",
"de-de",
"fr"
],
// "bundleTogether": false
// this can disable the bundling of locales
}
}
require("i18n/choose!./file.js"); // chooses the correct file by locale,
// but it do not merge the objects
require("i18n/concat!./file.js"); // concatinate all fitting locales
require("i18n/merge!./file.js"); // merges the resulting objects
// ./file.js is excuted while compiling
require("i18n!./file.json") == require("i18n/merge!json!./file.json")
Don't forget to polyfill require
if you want to use it in node.
See webpack
documentation.
MIT (http://www.opensource.org/licenses/mit-license.php)
The imports loader allows you to use modules that depend on specific global variables.
This is useful for third-party modules that rely on global variables like $
or this
being the window
object.
The imports loader can add the necessary require('whatever')
calls, so those modules work with webpack.
For further hints on compatibility issues, check out Shimming of the official docs.
⚠ By default loader generate ES module named syntax.
⚠ Be careful, existing imports (
import
/require
) in the original code and importing new values can cause failure.
To begin, you'll need to install imports-loader
:
$ npm install imports-loader --save-dev
Given you have this file:
example.js
$("img").doSomeAwesomeJqueryPluginStuff();
Then you can inject the jquery
value into the module by configuring the imports-loader
using two approaches.
The |
or %20
(space) allow to separate the syntax
, moduleName
, name
and alias
of import.
The documentation and syntax examples can be read here.
⚠
%20
is space in a query string, because you can't use spaces in URLs
// Alternative syntax:
//
// import myLib from 'imports-loader?imports=default%20jquery%20$!./example.js';
//
// `%20` is space in a query string, equivalently `default jquery $`
import myLib from "imports-loader?imports=default|jquery|$!./example.js";
// Adds the following code to the beginning of example.js:
//
// import $ from "jquery";
//
// ...
// Code
// ...
import myLib from "imports-loader?imports=default|jquery|$,angular!./example.js";
// `|` is separator in a query string, equivalently `default|jquery|$` and `angular`
// Adds the following code to the beginning of example.js:
//
// import $ from "jquery";
// import angular from "angular";
//
// ...
// Code
// ...
import myLib from "imports-loader?imports=named|library|myMethod,angular!./example.js";
// `|` is separator in a query string, equivalently `named|library|myMethod` and `angular`
// Adds the following code to the beginning of example.js:
//
// import { myMethod } from "library";
// import angular from "angular";
//
// ...
// Code
// ...
const myLib = require(`imports-loader?type=commonjs&imports=single|jquery|$,angular!./example.js`);
// `|` is separator in a query string, equivalently `single|jquery|$` and `angular`
// Adds the following code to the beginning of example.js:
//
// var $ = require("jquery");
// var angular = require("angular");
//
// ...
// Code
// ...
const myLib = require(`imports-loader?type=commonjs&imports=single|myLib|myMethod&wrapper=window&!./example.js`);
// `|` is separator in a query string, equivalently `single|myLib|myMethod` and `angular`
// Adds the following code to the example.js:
//
// const myMethod = require('myLib');
//
// (function () {
// ...
// Code
// ...
// }.call(window));
import myLib from "imports-loader?additionalCode=var%20myVariable%20=%20false;!./example.js";
// Adds the following code to the beginning of example.js:
//
// var myVariable = false;
//
// ...
// Code
// ...
webpack.config.js
module.exports = {
module: {
rules: [
{
// You can use `regexp`
// test: /example\.js/$
test: require.resolve("example.js"),
use: [
{
loader: "imports-loader",
options: {
imports: [
"default jquery $",
"default lib_2 lib_2_default",
"named lib_3 lib2_method_1",
"named lib_3 lib2_method_2 lib_2_method_2_short",
"namespace lib_4 my_namespace",
"side-effects lib_5",
{
syntax: "default",
moduleName: "angular",
name: "angular",
},
],
},
},
],
},
],
},
};
Generate output:
import $ from "jquery";
import lib_2_default from "lib_2";
import { lib2_method_1, lib2_method_2 as lib_2_method_2_short } from "lib_3";
import * as my_namespace from "lib_4";
import "lib_5";
import angular from "angular";
And run webpack
via your preferred method.
Name | Type | Default | Description |
---|---|---|---|
Name Type Default Description
|
{String} |
module |
Format of generated imports |
Name Type Default Description
|
{String\|Object\|Array<String\|Object>} |
undefined |
List of imports |
Name Type Default Description
|
{Boolean\|String\|Object} |
undefined |
Closes the module code in a function (
(function () { ... }).call();
) |
Name Type Default Description
|
{String} |
undefined |
Adds custom code |
type
Type: String
Default: module
Format of generated exports.
Possible values - commonjs
(CommonJS module syntax) and module
(ES module syntax).
commonjs
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("example.js"),
loader: "imports-loader",
options: {
syntax: "default",
type: "commonjs",
imports: "Foo",
},
},
],
},
};
Generate output:
var Foo = require("Foo");
// ...
// Code
// ...
module
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("example.js"),
loader: "imports-loader",
options: {
type: "module",
imports: "Foo",
},
},
],
},
};
Generate output:
import Foo from "Foo";
// ...
// Code
// ...
imports
Type: String|Object|Array<String|Object>
Default: undefined
List of imports.
String
Allows to use a string to describe an export.
Syntax
The |
or %20
(space) allow to separate the syntax
, moduleName
, name
and alias
of import.
String syntax - [[syntax] [moduleName] [name] [alias]]
or [[syntax]|[moduleName]|[name]|[alias]]
, where:
[syntax]
(may be omitted):
type
is module
- can be default
, named
, namespace
or side-effects
, the default value is default
.type
is commonjs
- can be single
, multiple
or pure
, the default value is single
.[moduleName]
- name of an imported module (required)
[name]
- name of an imported value (required)
[alias]
- alias of an imported value (may be omitted)
Examples:
If type module
:
[Foo]
- generates import Foo from "Foo";
.[default Foo]
- generates import Foo from "Foo";
.[default ./my-lib Foo]
- generates import Foo from "./my-lib";
.[named Foo FooA]
- generates import { FooA } from "Foo";
.[named Foo FooA Bar]
- generates import { FooA as Bar } from "Foo";
.[namespace Foo FooA]
- generates import * as FooA from "Foo";
.[side-effects Foo]
- generates import "Foo";
.If type commonjs
:
[Foo]
- generates const Foo = require("Foo");
.[single Foo]
- generates const Foo = require("Foo");
.[single ./my-lib Foo]
- generates const Foo = require("./my-lib");
.[multiple Foo FooA Bar]
- generates const { FooA: Bar } = require("Foo");
.[pure Foo]
- generates require("Foo");
.⚠ You need to set
type: "commonjs"
to usesingle
,multiple
andpure
syntaxes.⚠ Aliases can't be used together with
default
,namespace
,side-effects
,single
andpure
syntaxes.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("./path/to/example.js"),
loader: "imports-loader",
options: {
imports: "default lib myName",
},
},
],
},
};
Generate output:
import myName from "lib";
// ...
// Code
// ...
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("./path/to/example.js"),
loader: "imports-loader",
options: {
type: "commonjs",
imports: "single lib myName",
},
},
],
},
};
Generate output:
var myName = require("lib");
// ...
// Code
// ...
Object
Allows to use an object to describe an import.
Properties:
syntax
:
type
is module
- can be default
, named
, namespace
or side-effects
type
is commonjs
- can be single
, multiple
or pure
moduleName
- name of an imported module (required)
name
- name of an imported value (required)
alias
- alias of an imported value (may be omitted)
⚠ Alias can't be used together with
default
,namespace
,side-effects
,single
andpure
syntaxes.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("example.js"),
use: [
{
loader: "imports-loader",
options: {
imports: {
syntax: "named",
moduleName: "lib_2",
name: "lib2_method_2",
alias: "lib_2_method_2_alias",
},
},
},
],
},
],
},
};
Generate output:
import { lib2_method_2 as lib_2_method_2_alias } from "lib_2";
// ...
// Code
// ...
Array
Allow to specify multiple imports.
Each item can be a string
or an object
.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("example.js"),
use: [
{
loader: "imports-loader",
options: {
imports: [
{
moduleName: "angular",
},
{
syntax: "default",
moduleName: "jquery",
name: "$",
},
"default lib_2 lib_2_default",
"named lib_2 lib2_method_1",
"named lib_2 lib2_method_2 lib_2_method_2_alias",
"namespace lib_3 lib_3_all",
"side-effects lib_4",
],
},
},
],
},
],
},
};
Generate output:
import angular from "angular";
import $ from "jquery";
import lib_2_default from "lib_2";
import { lib2_method_1, lib2_method_2 as lib_2_method_2_alias } from "lib_2";
import * as lib_3_all from "lib_3";
import "lib_4";
// ...
// Code
// ...
wrapper
Type: Boolean|String|Object
Default: undefined
Closes the module code in a function with a given thisArg
and args
((function () { ... }).call();
).
⚠ Do not use this option if source code contains ES module import(s)
Boolean
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("example.js"),
use: [
{
loader: "imports-loader",
options: {
imports: {
moduleName: "jquery",
name: "$",
},
wrapper: true,
},
},
],
},
],
},
};
Generate output:
import $ from "jquery";
(function () {
// ...
// Code
// ...
}.call());
String
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("example.js"),
use: [
{
loader: "imports-loader",
options: {
imports: {
moduleName: "jquery",
name: "$",
},
wrapper: "window",
},
},
],
},
],
},
};
Generate output:
import $ from "jquery";
(function () {
// ...
// Code
// ...
}.call(window));
Object
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("example.js"),
use: [
{
loader: "imports-loader",
options: {
imports: {
moduleName: "jquery",
name: "$",
},
wrapper: {
thisArg: "window",
args: ["myVariable", "myOtherVariable"],
},
},
},
],
},
],
},
};
Generate output:
import $ from "jquery";
(function (myVariable, myOtherVariable) {
// ...
// Code
// ...
}.call(window, myVariable, myOtherVariable));
Object
with different parameter nameswebpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("example.js"),
use: [
{
loader: "imports-loader",
options: {
imports: {
moduleName: "jquery",
name: "$",
},
wrapper: {
thisArg: "window",
args: {
myVariable: "var1",
myOtherVariable: "var2",
},
},
},
},
],
},
],
},
};
Generate output:
import $ from "jquery";
(function (var1, var2) {
// ...
// Code
// ...
}.call(window, myVariable, myOtherVariable));
additionalCode
Type: String
Default: undefined
Adds custom code as a preamble before the module's code.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("example.js"),
use: [
{
loader: "imports-loader",
options: {
imports: {
moduleName: "jquery",
name: "$",
},
additionalCode: "var myVariable = false;",
},
},
],
},
],
},
};
Generate output:
import $ from "jquery";
var myVariable = false;
// ...
// Code
// ...
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("example.js"),
use: [
{
loader: "imports-loader",
options: {
imports: {
moduleName: "jquery",
name: "$",
},
additionalCode:
"var define = false; /* Disable AMD for misbehaving libraries */",
},
},
],
},
],
},
};
Generate output:
import $ from "jquery";
var define = false; /* Disable AMD for misbehaving libraries */
// ...
// Code
// ...
Please take a moment to read our contributing guidelines if you haven't yet done so.
Instrument JS files with istanbul-lib-instrument for subsequent code coverage reporting
npm i -D istanbul-instrumenter-loader
References
Structure
├─ src
│ |– components
│ | |– bar
│ | │ |─ index.js
│ | |– foo/
│ |– index.js
|– test
| |– src
| | |– components
| | | |– foo
| | | | |– index.js
To create a code coverage report for all components (even for those for which you have no tests yet) you have to require all the 1) sources and 2) tests. Something like it's described in "alternative usage" of karma-webpack
test/index.js
// requires all tests in `project/test/src/components/**/index.js`
const tests = require.context('./src/components/', true, /index\.js$/);
tests.keys().forEach(tests);
// requires all components in `project/src/components/**/index.js`
const components = require.context('../src/components/', true, /index\.js$/);
components.keys().forEach(components);
ℹ️ This file will be the only
entry
point forkarma
karma.conf.js
config.set({
...
files: [
'test/index.js'
],
preprocessors: {
'test/index.js': 'webpack'
},
webpack: {
...
module: {
rules: [
// instrument only testing sources with Istanbul
{
test: /\.js$/,
use: { loader: 'istanbul-instrumenter-loader' },
include: path.resolve('src/components/')
}
]
}
...
},
reporters: [ 'progress', 'coverage-istanbul' ],
coverageIstanbulReporter: {
reports: [ 'text-summary' ],
fixWebpackSourcePaths: true
}
...
});
Babel
You must run the instrumentation as a post step
webpack.config.js
{
test: /\.js$|\.jsx$/,
use: {
loader: 'istanbul-instrumenter-loader',
options: { esModules: true }
},
enforce: 'post',
exclude: /node_modules|\.spec\.js$/,
}
The loader supports all options supported by istanbul-lib-instrument
Name | Type | Default | Description |
---|---|---|---|
Name Type Default Description
|
{Boolean} |
false |
Turn on debugging mode |
Name Type Default Description
|
{Boolean} |
true |
Generate compact code |
Name Type Default Description
|
{Boolean} |
false |
Set to
true
to allow return statements outside of functions |
Name Type Default Description
|
{Boolean} |
false |
Set to
true
to instrument ES2015 Modules |
Name Type Default Description
|
{String} |
__coverage__ |
Name of global coverage variable |
Name Type Default Description
|
{Boolean} |
false |
Preserve comments in
output |
Name Type Default Description
|
{Boolean} |
false |
Set to
true
to produce a source map for the instrumented code |
Name Type Default Description
|
{Function} |
null |
A callback function that is called when a source map URL is found in the original code. This function is called with the source filename and the source map URL |
webpack.config.js
{
test: /\.js$/,
use: {
loader: 'istanbul-instrumenter-loader',
options: {...options}
}
}
Kir Belevich | Juho Vepsäläinen | Joshua Wiens | Michael Ciniawsky | Matt Lewis |
A JSHint loader module for webpack. Runs JSHint on JavaScript files in a bundle at build-time.
This module requires a minimum of Node v6.9.0 and Webpack v4.0.0.
To begin, you'll need to install jshint-loader
:
$ npm install jshint-loader --save-dev
Then add the loader to your webpack
config. For example:
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /.js/,
enforce: 'pre',
exclude: /node_modules/,
use: [
{
loader: `jshint-loader`,
options: {...options}
}
]
}
]
}
}
And run webpack
via your preferred method.
All valid JSHint options are valid on this object, in addition to the custom loader options listed below:
delete options.; delete options.; delete options.;
emitErrors
Type: Boolean
Default: undefined
Instructs the loader to emit all JSHint warnings and errors as webpack errors.
failOnHint
Type: Boolean
Default: undefined
Instructs the loader to cause the webpack build to fail on all JSHint warnings and errors.
reporter
Type: Function
Default: undefined
A function used to format and emit JSHint warnings and errors.
By default, jshint-loader
will provide a default reporter.
However, if you prefer a custom reporter, pass a function under the reporter
property in jshint
options. (see usage above)
The reporter function will be passed an array of errors/warnings produced by JSHint with the following structure:
[
{
id: [string, usually '(error)'],
code: [string, error/warning code],
reason: [string, error/warning message],
evidence: [string, a piece of code that generated this error]
line: [number]
character: [number]
scope: [string, message scope;
usually '(main)' unless the code was eval'ed]
[+ a few other legacy fields that you don't need to worry about.]
},
// ...
// more errors/warnings
]
The reporter function will be excuted with the loader context as this
. You may
emit messages using this.emitWarning(...)
or this.emitError(...)
. See
webpack docs on loader context.
Note: JSHint reporters are not compatible with JSHint-loader! This is due to the fact that reporter input is only processed from one file; not multiple files. Error reporting in this manner differs from traditional reporters for JSHint since the loader plugin (i.e. JSHint-loader) is executed for each source file; and thus the reporter is executed for each file.
The output in webpack CLI will usually be:
...
WARNING in ./path/to/file.js
<reporter output>
...
`
Please take a moment to read our contributing guidelines if you haven't yet done so.
npm install --save-dev json-loader
⚠️ Since
webpack >= v2.0.0
, importing of JSON files will work by default. You might still want to use this if you use a custom file extension. See the v1.0.0 -> v2.0.0 Migration Guide for more information
Inline
const json = require('json-loader!./file.json');
Configuration
(recommended)const json = require('./file.json');
webpack.config.js
module.exports = {
module: {
loaders: [
{
test: /\.json$/,
loader: 'json-loader'
}
]
}
}
Tobias Koppers |
A webpack loader for parsing json5 files into JavaScript objects.
To begin, you'll need to install json5-loader
:
$ npm install json5-loader --save-dev
You can use the loader either:
json5-loader
in the module.rules
object of the webpack configuration, orjson5-loader!
prefix to the require statement.Suppose we have the following json5
file:
file.json5
{
env: 'production',
passwordStrength: 'strong',
}
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.json5$/i,
loader: 'json5-loader',
type: 'javascript/auto',
},
],
},
};
Name | Type | Default | Description |
---|---|---|---|
Name Type Default Description
|
{Boolean} |
true |
Uses ES modules syntax |
esModule
Type: Boolean
Default: true
There are some cases in which using ES modules is beneficial, like in the case of module concatenation and tree shaking.
You can enable a ES module syntax using:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.json5$/i,
loader: 'json5-loader',
options: {
esModule: false,
},
type: 'javascript/auto',
},
],
},
};
file.json5
{
env: 'production',
passwordStrength: 'strong',
}
index.js
import appConfig from 'json5-loader!./file.json5';
console.log(appConfig.env); // 'production'
Don't forget to polyfill require if you want to use it in Node.js. See the webpack documentation.
Please take a moment to read our contributing guidelines if you haven't yet done so.
A Less loader for webpack. Compiles Less to CSS.
To begin, you'll need to install less
and less-loader
:
$ npm install less less-loader --save-dev
Then add the loader to your webpack
config. For example:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.less$/i,
loader: [
// compiles Less to CSS
"style-loader",
"css-loader",
"less-loader",
],
},
],
},
};
And run webpack
via your preferred method.
Name | Type | Default | Description |
---|---|---|---|
Name Type Default Description
|
{Object\|Function} |
{ relativeUrls: true } |
Options for Less. |
Name Type Default Description
|
{String\|Function} |
undefined |
Prepends/Appends
Less
code to the actual entry file. |
Name Type Default Description
|
{Boolean} |
compiler.devtool |
Enables/Disables generation of source maps. |
Name Type Default Description
|
{Boolean} |
true |
Enables/Disables the default Webpack importer. |
Name Type Default Description
|
{Object\|String} |
less |
Setup Less implementation to use. |
lessOptions
Type: Object|Function
Default: { relativeUrls: true }
You can pass any Less specific options to the less-loader
through the lessOptions
property in the loader options. See the Less documentation for all available options in dash-case. Since we're passing these options to Less programmatically, you need to pass them in camelCase here:
Object
Use an object to pass options through to Less.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.less$/i,
use: [
{
loader: "style-loader",
},
{
loader: "css-loader",
},
{
loader: "less-loader",
options: {
lessOptions: {
strictMath: true,
},
},
},
],
},
],
},
};
Function
Allows setting the options passed through to Less based off of the loader context.
module.exports = {
module: {
rules: [
{
test: /\.less$/i,
use: [
"style-loader",
"css-loader",
{
loader: "less-loader",
options: {
lessOptions: (loaderContext) => {
// More information about available properties https://webpack.js.org/api/loaders/
const { resourcePath, rootContext } = loaderContext;
const relativePath = path.relative(rootContext, resourcePath);
if (relativePath === "styles/foo.less") {
return {
paths: ["absolute/path/c", "absolute/path/d"],
};
}
return {
paths: ["absolute/path/a", "absolute/path/b"],
};
},
},
},
],
},
],
},
};
additionalData
Type: String|Function
Default: undefined
Prepends Less
code before the actual entry file.
In this case, the less-loader
will not override the source but just prepend the entry's content.
This is especially useful when some of your Less variables depend on the environment:
ℹ Since you're injecting code, this will break the source mappings in your entry file. Often there's a simpler solution than this, like multiple Less entry files.
String
module.exports = {
module: {
rules: [
{
test: /\.less$/i,
use: [
"style-loader",
"css-loader",
{
loader: "less-loader",
options: {
additionalData: `@env: ${process.env.NODE_ENV};`,
},
},
],
},
],
},
};
Function
module.exports = {
module: {
rules: [
{
test: /\.less$/i,
use: [
"style-loader",
"css-loader",
{
loader: "less-loader",
options: {
additionalData: (content, loaderContext) => {
// More information about available properties https://webpack.js.org/api/loaders/
const { resourcePath, rootContext } = loaderContext;
const relativePath = path.relative(rootContext, resourcePath);
if (relativePath === "styles/foo.less") {
return "@value: 100px;" + content;
}
return "@value: 200px;" + content;
},
},
},
],
},
],
},
};
module.exports = {
module: {
rules: [
{
test: /\.less$/i,
use: [
"style-loader",
"css-loader",
{
loader: "less-loader",
options: {
additionalData: async (content, loaderContext) => {
// More information about available properties https://webpack.js.org/api/loaders/
const { resourcePath, rootContext } = loaderContext;
const relativePath = path.relative(rootContext, resourcePath);
if (relativePath === "styles/foo.less") {
return "@value: 100px;" + content;
}
return "@value: 200px;" + content;
},
},
},
],
},
],
},
};
sourceMap
Type: Boolean
Default: depends on the compiler.devtool
value
By default generation of source maps depends on the devtool
option. All values enable source map generation except eval
and false
value.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.less$/i,
use: [
"style-loader",
{
loader: "css-loader",
options: {
sourceMap: true,
},
},
{
loader: "less-loader",
options: {
sourceMap: true,
},
},
],
},
],
},
};
webpackImporter
Type: Boolean
Default: true
Enables/Disables the default webpack
importer.
This can improve performance in some cases. Use it with caution because aliases and @import
at-rules starting with ~
will not work.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.less$/i,
use: [
"style-loader",
"css-loader",
{
loader: "less-loader",
options: {
webpackImporter: false,
},
},
],
},
],
},
};
implementation
Type: Object | String
⚠ less-loader compatible with Less 3 and 4 versions
The special implementation
option determines which implementation of Less to use. Overrides the locally installed peerDependency
version of less
.
This option is only really useful for downstream tooling authors to ease the Less 3-to-4 transition.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.less$/i,
use: [
"style-loader",
"css-loader",
{
loader: "less-loader",
options: {
implementation: require("less"),
},
},
],
},
],
},
};
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.less$/i,
use: [
"style-loader",
"css-loader",
{
loader: "less-loader",
options: {
implementation: require.resolve("less"),
},
},
],
},
],
},
};
Chain the less-loader
with the css-loader
and the style-loader
to immediately apply all styles to the DOM.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.less$/i,
use: [
{
loader: "style-loader", // creates style nodes from JS strings
},
{
loader: "css-loader", // translates CSS into CommonJS
},
{
loader: "less-loader", // compiles Less to CSS
},
],
},
],
},
};
Unfortunately, Less doesn't map all options 1-by-1 to camelCase. When in doubt, check their executable and search for the dash-case option.
To enable sourcemaps for CSS, you'll need to pass the sourceMap
property in the loader's options. If this is not passed, the loader will respect the setting for webpack source maps, set in devtool
.
webpack.config.js
module.exports = {
devtool: "source-map", // any "source-map"-like devtool is possible
module: {
rules: [
{
test: /\.less$/i,
use: [
"style-loader",
{
loader: "css-loader",
options: {
sourceMap: true,
},
},
{
loader: "less-loader",
options: {
sourceMap: true,
},
},
],
},
],
},
};
If you want to edit the original Less files inside Chrome, there's a good blog post. The blog post is about Sass but it also works for Less.
Usually, it's recommended to extract the style sheets into a dedicated file in production using the MiniCssExtractPlugin. This way your styles are not dependent on JavaScript.
First we try to use built-in less
resolve logic, then webpack
resolve logic (aliases and ~
).
webpack
provides an advanced mechanism to resolve files.
less-loader
applies a Less plugin that passes all queries to the webpack resolver if less
could not resolve @import
.
Thus you can import your Less modules from node_modules
.
@import "bootstrap/less/bootstrap";
Using ~
is deprecated and can be removed from your code (we recommend it), but we still support it for historical reasons.
Why you can removed it? The loader will first try to resolve @import
as relative, if it cannot be resolved, the loader will try to resolve @import
inside node_modules
.
Just prepend them with a ~
which tells webpack to look up the modules
.
@import "~bootstrap/less/bootstrap";
Default resolver options can be modified by resolve.byDependency
:
webpack.config.js
module.exports = {
devtool: "source-map", // any "source-map"-like devtool is possible
module: {
rules: [
{
test: /\.less$/i,
use: ["style-loader", "css-loader", "less-loader"],
},
],
},
resolve: {
byDependency: {
// More options can be found here https://webpack.js.org/configuration/resolve/
less: {
mainFiles: ["custom"],
},
},
},
};
It's important to only prepend it with ~
, because ~/
resolves to the home-directory. webpack needs to distinguish between bootstrap
and ~bootstrap
, because CSS and Less files have no special syntax for importing relative files. Writing @import "file"
is the same as @import "./file";
If you specify the paths
option, modules will be searched in the given paths
. This is less
default behavior. paths
should be an array with absolute paths:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.less$/i,
use: [
{
loader: "style-loader",
},
{
loader: "css-loader",
},
{
loader: "less-loader",
options: {
lessOptions: {
paths: [path.resolve(__dirname, "node_modules")],
},
},
},
],
},
],
},
};
In order to use plugins, simply set the plugins
option like this:
webpack.config.js
const CleanCSSPlugin = require('less-plugin-clean-css');
module.exports = {
...
{
loader: 'less-loader',
options: {
lessOptions: {
plugins: [
new CleanCSSPlugin({ advanced: true }),
],
},
},
},
...
};
ℹ️ Access to the loader context inside the custom plugin can be done using the
pluginManager.webpackLoaderContext
property.
module.exports = {
install: function (less, pluginManager, functions) {
functions.add("pi", function () {
// Loader context is available in `pluginManager.webpackLoaderContext`
return Math.PI;
});
},
};
Bundling CSS with webpack has some nice advantages like referencing images and fonts with hashed urls or hot module replacement in development. In production, on the other hand, it's not a good idea to apply your style sheets depending on JS execution. Rendering may be delayed or even a FOUC might be visible. Thus it's often still better to have them as separate files in your final production build.
There are two possibilities to extract a style sheet from the bundle:
extract-loader
(simpler, but specialized on the css-loader's output)There is a known problem with Less and CSS modules regarding relative file paths in url(...)
statements. See this issue for an explanation.
Please take a moment to read our contributing guidelines if you haven't yet done so.
Allows Mocha tests to be loaded and run via webpack.
To begin, you'll need to install mocha-loader
and mocha
:
npm install --save-dev mocha-loader mocha
Then add the plugin to your webpack
config. For example:
file.js
import test from './test.js';
webpack.config.js
module.exports = {
entry: './entry.js',
output: {
path: __dirname,
filename: 'bundle.js',
},
module: {
rules: [
{
test: /test\.js$/,
use: 'mocha-loader',
exclude: /node_modules/,
},
],
},
};
And run webpack
via your preferred method.
Alternative usage (without configuration):
import test from 'mocha-loader!./test.js';
No options for loader.
file.js
module.exports = true;
test.js
describe('Test', () => {
it('should succeed', (done) => {
setTimeout(done, 1000);
});
it('should fail', () => {
setTimeout(() => {
throw new Error('Failed');
}, 1000);
});
it('should randomly fail', () => {
if (require('./module')) {
throw new Error('Randomly failed');
}
});
});
Please take a moment to read our contributing guidelines if you haven't yet done so.
A webpack
loader for splitting modules and using multiple loaders. This loader
requires a module multiple times, each time loaded with different loaders, as
defined in your config.
Note: In a multi-entry, the exports of the last item are exported.
This module requires a minimum of Node v6.9.0 and Webpack v4.0.0.
To begin, you'll need to install multi-loader
:
$ npm install multi-loader --save-dev
Then add the loader to your webpack
config. For example:
// webpack.config.js
const multi = require('multi-loader');
{
module: {
loaders: [
{
test: /\.css$/,
// Add CSS to the DOM and return the raw content
loader: multi(
'style-loader!css-loader!autoprefixer-loader',
'raw-loader'
)
}
]
}
}
And run webpack
via your preferred method.
A Node.js add-ons loader.
Allows to connect native node modules with .node
extension.
⚠
node-loader
only works on thenode
/async-node
/electron-main
/electron-renderer
/electron-preload
targets.
To begin, you'll need to install node-loader
:
$ npm install node-loader --save-dev
Setup the target
option to node
/async-node
/electron-main
/electron-renderer
/electron-preload
value and do not mock the __dirname
global variable.
webpack.config.js
module.exports = {
target: "node",
node: {
__dirname: false,
},
module: {
rules: [
{
test: /\.node$/,
loader: "node-loader",
},
],
},
};
index.js
import node from "node-loader!./file.node";
And run webpack
via your preferred method.
index.js
import node from "file.node";
Then add the loader to your webpack
config. For example:
webpack.config.js
module.exports = {
target: "node",
node: {
__dirname: false,
},
module: {
rules: [
{
test: /\.node$/,
loader: "node-loader",
},
],
},
};
And run webpack
via your preferred method.
Name | Type | Default | Description |
---|---|---|---|
Name Type Default Description
|
{Number} |
undefined |
Enables/Disables
url
/
image-set
functions handling |
Name Type Default Description
|
{String\|Function} |
'[contenthash].[ext]' |
Specifies a custom filename template for the target file(s). |
flags
Type: Number
Default: undefined
The flags
argument is an integer that allows to specify dlopen behavior.
See the process.dlopen
documentation for details.
index.js
import node from "file.node";
webpack.config.js
const os = require("os");
module.exports = {
target: "node",
node: {
__dirname: false,
},
module: {
rules: [
{
test: /\.node$/,
loader: "node-loader",
options: {
flags: os.constants.dlopen.RTLD_NOW,
},
},
],
},
};
name
Type: String|Function
Default: '[contenthash].[ext]'
Specifies a custom filename template for the target file(s).
String
webpack.config.js
module.exports = {
target: "node",
node: {
__dirname: false,
},
module: {
rules: [
{
test: /\.node$/,
loader: "node-loader",
options: {
name: "[path][name].[ext]",
},
},
],
},
};
Function
webpack.config.js
module.exports = {
target: "node",
node: {
__dirname: false,
},
module: {
rules: [
{
test: /\.node$/,
loader: "node-loader",
options: {
name(resourcePath, resourceQuery) {
// `resourcePath` - `/absolute/path/to/file.js`
// `resourceQuery` - `?foo=bar`
if (process.env.NODE_ENV === "development") {
return "[path][name].[ext]";
}
return "[contenthash].[ext]";
},
},
},
],
},
};
Please take a moment to read our contributing guidelines if you haven't yet done so.
A webpack loader that returns an empty module.
One use for this loader is to silence modules imported by a dependency. Say, for example, your project relies on an ES6 library that imports a polyfill you don't need, so removing it will cause no loss in functionality.
To begin, you'll need to install null-loader
:
$ npm install null-loader --save-dev
Then add the loader to your webpack
config. For example:
// webpack.config.js
const path = require('path');
module.exports = {
module: {
rules: [
{
// Test for a polyfill (or any file) and it won't be included in your
// bundle
test: path.resolve(__dirname, 'node_modules/library/polyfill.js'),
use: 'null-loader',
},
],
},
};
And run webpack
via your preferred method.
Please take a moment to read our contributing guidelines if you haven't yet done so.
The loader processes Polymer 3 template elements to minify the html and add images, fonts and imported stylesheets to the webpack dependency graph.
Looking for the Polymer 2 version? See the Polymer 2 branch
{
test: /\.js$/,
options: {
htmlLoader: Object (optional)
},
loader: 'polymer-webpack-loader'
},
Options to pass to the html-loader. See html-loader.
If you'd like to transpile the contents of your element you can chain an additional loader.
module: {
loaders: [
{
test: /\.html$/,
use: [
// Chained loaders are applied last to first
{ loader: 'babel-loader' },
{ loader: 'polymer-webpack-loader' }
]
}
]
}
// alternative syntax
module: {
loaders: [
{
test: /\.html$/,
// Chained loaders are applied right to left
loader: 'babel-loader!polymer-webpack-loader'
}
]
}
The webcomponent polyfills must be added in a specific order. If you do not delay loading the main bundle with your components, you will see the following exceptions in the browser console:
Uncaught TypeError: Failed to construct 'HTMLElement': Please use the 'new' operator, this DOM object constructor cannot be called as a function.
Reference the demo html file for the proper loading sequence.
Bryan Coulter | Chad Killingsworth | Rob Dodson |
Loader to process CSS with PostCSS
.
You need webpack v5 to use the latest version. For Webpack v4, you have to install postcss-loader v4.
To begin, you'll need to install postcss-loader
and postcss
:
npm install --save-dev postcss-loader postcss
Then add the plugin to your webpack
config. For example:
In the following configuration the plugin
postcss-preset-env
is used, which is not installed by default.
file.js
import css from "file.css";
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
"style-loader",
"css-loader",
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: [
[
"postcss-preset-env",
{
// Options
},
],
],
},
},
},
],
},
],
},
};
Alternative use with config files:
postcss.config.js
module.exports = {
plugins: [
[
"postcss-preset-env",
{
// Options
},
],
],
};
The loader automatically searches for configuration files.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: ["style-loader", "css-loader", "postcss-loader"],
},
],
},
};
And run webpack
via your preferred method.
Name | Type | Default | Description |
---|---|---|---|
Name Type Default Description
|
{Boolean} |
undefined |
Enable PostCSS Parser support in
CSS-in-JS |
Name Type Default Description
|
{Object\|Function} |
defaults values for Postcss.process |
Set
PostCSS
options and plugins |
Name Type Default Description
|
{Boolean} |
compiler.devtool |
Enables/Disables generation of source maps |
Name Type Default Description
|
{Function\|String} |
postcss |
Setup PostCSS implementation to use |
execute
Type: Boolean
Default: undefined
If you use JS styles the postcss-js
parser, add the execute
option.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.style.js$/,
use: [
"style-loader",
{
loader: "css-loader",
},
{
loader: "postcss-loader",
options: {
postcssOptions: {
parser: "postcss-js",
},
execute: true,
},
},
],
},
],
},
};
postcssOptions
Type: Object|Function
Default: undefined
Allows to set PostCSS options
and plugins.
All PostCSS
options are supported.
There is the special config
option for config files. How it works and how it can be configured is described below.
We recommend do not specify from
, to
and map
options, because this can lead to wrong path in source maps.
If you need source maps please use the sourcemap
option.
Object
Setup plugins
:
webpack.config.js (recommended)
const myOtherPostcssPlugin = require("postcss-my-plugin");
module.exports = {
module: {
rules: [
{
test: /\.sss$/i,
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: [
"postcss-import",
["postcss-short", { prefix: "x" }],
require.resolve("my-postcss-plugin"),
myOtherPostcssPlugin({ myOption: true }),
// Deprecated and will be removed in the next major release
{ "postcss-nested": { preserveEmpty: true } },
],
},
},
},
],
},
};
webpack.config.js (deprecated, will be removed in the next major release)
module.exports = {
module: {
rules: [
{
test: /\.sss$/i,
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: {
"postcss-import": {},
"postcss-short": { prefix: "x" },
},
},
},
},
],
},
};
Setup syntax
:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.sss$/i,
loader: "postcss-loader",
options: {
postcssOptions: {
// Can be `String`
syntax: "sugarss",
// Can be `Object`
syntax: require("sugarss"),
},
},
},
],
},
};
Setup parser
:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.sss$/i,
loader: "postcss-loader",
options: {
postcssOptions: {
// Can be `String`
parser: "sugarss",
// Can be `Object`
parser: require("sugarss"),
// Can be `Function`
parser: require("sugarss").parse,
},
},
},
],
},
};
Setup stringifier
:
webpack.config.js
const Midas = require("midas");
const midas = new Midas();
module.exports = {
module: {
rules: [
{
test: /\.sss$/i,
loader: "postcss-loader",
options: {
postcssOptions: {
// Can be `String`
stringifier: "sugarss",
// Can be `Object`
stringifier: require("sugarss"),
// Can be `Function`
stringifier: midas.stringifier,
},
},
},
],
},
};
Function
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(css|sss)$/i,
loader: "postcss-loader",
options: {
postcssOptions: (loaderContext) => {
if (/\.sss$/.test(loaderContext.resourcePath)) {
return {
parser: "sugarss",
plugins: [
["postcss-short", { prefix: "x" }],
"postcss-preset-env",
],
};
}
return {
plugins: [
["postcss-short", { prefix: "x" }],
"postcss-preset-env",
],
};
},
},
},
],
},
};
config
Type: Boolean|String
Default: undefined
Allows to set options using config files. Options specified in the config file are combined with options passed to the loader, the loader options overwrite options from config.
The loader will search up the directory tree for configuration in the following places:
postcss
property in package.json
.postcssrc
file in JSON or YAML format.postcssrc.json
, .postcssrc.yaml
, .postcssrc.yml
, .postcssrc.js
, or .postcssrc.cjs
filepostcss.config.js
or postcss.config.cjs
CommonJS module exporting an object (recommended)Using Object
notation:
postcss.config.js (recommend)
module.exports = {
// You can specify any options from https://postcss.org/api/#processoptions here
// parser: 'sugarss',
plugins: [
// Plugins for PostCSS
["postcss-short", { prefix: "x" }],
"postcss-preset-env",
],
};
Using Function
notation:
postcss.config.js (recommend)
module.exports = (api) => {
// `api.file` - path to the file
// `api.mode` - `mode` value of webpack, please read https://webpack.js.org/configuration/mode/
// `api.webpackLoaderContext` - loader context for complex use cases
// `api.env` - alias `api.mode` for compatibility with `postcss-cli`
// `api.options` - the `postcssOptions` options
if (/\.sss$/.test(api.file)) {
return {
// You can specify any options from https://postcss.org/api/#processoptions here
parser: "sugarss",
plugins: [
// Plugins for PostCSS
["postcss-short", { prefix: "x" }],
"postcss-preset-env",
],
};
}
return {
// You can specify any options from https://postcss.org/api/#processoptions here
plugins: [
// Plugins for PostCSS
["postcss-short", { prefix: "x" }],
"postcss-preset-env",
],
};
};
postcss.config.js (deprecated, will be removed in the next major release)
module.exports = {
// You can specify any options from https://postcss.org/api/#processoptions here
// parser: 'sugarss',
plugins: {
// Plugins for PostCSS
"postcss-short": { prefix: "x" },
"postcss-preset-env": {},
},
};
You can use different postcss.config.js
files in different directories.
Config lookup starts from path.dirname(file)
and walks the file tree upwards until a config file is found.
|– components
| |– component
| | |– index.js
| | |– index.png
| | |– style.css (1)
| | |– postcss.config.js (1)
| |– component
| | |– index.js
| | |– image.png
| | |– style.css (2)
|
|– postcss.config.js (1 && 2 (recommended))
|– webpack.config.js
|
|– package.json
After setting up your postcss.config.js
, add postcss-loader
to your webpack.config.js
.
You can use it standalone or in conjunction with css-loader
(recommended).
Use it before css-loader
and style-loader
, but after other preprocessor loaders like e.g sass|less|stylus-loader
, if you use any (since webpack loaders evaluate right to left/bottom to top).
webpack.config.js (recommended)
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [
"style-loader",
{
loader: "css-loader",
options: {
importLoaders: 1,
},
},
"postcss-loader",
],
},
],
},
};
Enables/Disables autoloading config.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "postcss-loader",
options: {
postcssOptions: {
config: false,
},
},
},
],
},
};
Allows to specify the path to the config file.
webpack.config.js
const path = require("path");
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "postcss-loader",
options: {
postcssOptions: {
config: path.resolve(__dirname, "custom.config.js"),
},
},
},
],
},
};
sourceMap
Type: Boolean
Default: depends on the compiler.devtool
value
By default generation of source maps depends on the devtool
option.
All values enable source map generation except eval
and false
value.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
{ loader: "style-loader" },
{ loader: "css-loader", options: { sourceMap: true } },
{ loader: "postcss-loader", options: { sourceMap: true } },
{ loader: "sass-loader", options: { sourceMap: true } },
],
},
],
},
};
Alternative setup:
webpack.config.js
module.exports = {
devtool: "source-map",
module: {
rules: [
{
test: /\.css$/i,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
{ loader: "postcss-loader" },
{ loader: "sass-loader" },
],
},
],
},
};
implementation
Type: Function | String
Default: postcss
The special implementation
option determines which implementation of PostCSS to use. Overrides the locally installed peerDependency
version of postcss
.
This option is only really useful for downstream tooling authors to ease the PostCSS 7-to-8 transition.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
{
loader: "postcss-loader",
options: { implementation: require("postcss") },
},
{ loader: "sass-loader" },
],
},
],
},
};
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
{
loader: "postcss-loader",
options: { implementation: require.resolve("postcss") },
},
{ loader: "sass-loader" },
],
},
],
},
};
You'll need to install sugarss
:
npm install --save-dev sugarss
Using SugarSS
syntax.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.sss$/i,
use: [
"style-loader",
{
loader: "css-loader",
options: { importLoaders: 1 },
},
{
loader: "postcss-loader",
options: {
postcssOptions: {
parser: "sugarss",
},
},
},
],
},
],
},
};
You'll need to install autoprefixer
:
npm install --save-dev autoprefixer
Add vendor prefixes to CSS rules using autoprefixer
.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
"style-loader",
{
loader: "css-loader",
options: { importLoaders: 1 },
},
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: [
[
"autoprefixer",
{
// Options
},
],
],
},
},
},
],
},
],
},
};
:warning:
postcss-preset-env
includesautoprefixer
, so adding it separately is not necessary if you already use the preset. More information
You'll need to install postcss-preset-env
:
npm install --save-dev postcss-preset-env
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
"style-loader",
{
loader: "css-loader",
options: { importLoaders: 1 },
},
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: [
[
"postcss-preset-env",
{
// Options
},
],
],
},
},
},
],
},
],
},
};
What is CSS Modules
? Please read.
No additional options required on the postcss-loader
side.
To make them work properly, either add the css-loader
’s importLoaders
option.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
"style-loader",
{
loader: "css-loader",
options: {
modules: true,
importLoaders: 1,
},
},
"postcss-loader",
],
},
],
},
};
postcss-js
You'll need to install postcss-js
:
npm install --save-dev postcss-js
If you want to process styles written in JavaScript, use the postcss-js
parser.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.style.js$/,
use: [
"style-loader",
{
loader: "css-loader",
options: {
importLoaders: 2,
},
},
{
loader: "postcss-loader",
options: {
postcssOptions: {
parser: "postcss-js",
},
execute: true,
},
},
"babel-loader",
],
},
],
},
};
As result you will be able to write styles in the following way
import colors from "./styles/colors";
export default {
".menu": {
color: colors.main,
height: 25,
"&_link": {
color: "white",
},
},
};
:warning: If you are using Babel you need to do the following in order for the setup to work
- Add
babel-plugin-add-module-exports
to your configuration.- You need to have only one default export per style module.
Using mini-css-extract-plugin
.
webpack.config.js
const isProductionMode = process.env.NODE_ENV === "production";
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
mode: isProductionMode ? "production" : "development",
module: {
rules: [
{
test: /\.css$/,
use: [
isProductionMode ? MiniCssExtractPlugin.loader : "style-loader",
"css-loader",
"postcss-loader",
],
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: isProductionMode ? "[name].[contenthash].css" : "[name].css",
}),
],
};
To write a asset from PostCSS plugin to the webpack, need to add a message in result.messages
.
The message should contain the following fields:
type
= asset
- Message type (require, should be equal asset
)file
- file name (require)content
- file content (require)sourceMap
- sourceMapinfo
- asset infowebpack.config.js
const customPlugin = () => (css, result) => {
result.messages.push({
type: "asset",
file: "sprite.svg",
content: "<svg>...</svg>",
});
};
const postcssPlugin = postcss.plugin("postcss-assets", customPlugin);
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
"style-loader",
"css-loader",
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: [postcssPlugin()],
},
},
},
],
},
],
},
};
The dependencies are necessary for webpack to understand when it needs to run recompilation on the changed files.
There are two way to add dependencies:
result.messages
.The message should contain the following fields:
type
= dependency
- Message type (require, should be equal dependency
, context-dependency
, build-dependency
or missing-dependency
)file
- absolute file path (require)webpack.config.js
const path = require("path");
const customPlugin = () => (css, result) => {
result.messages.push({
type: "dependency",
file: path.resolve(__dirname, "path", "to", "file"),
});
};
const postcssPlugin = postcss.plugin("postcss-assets", customPlugin);
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
"style-loader",
"css-loader",
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: [postcssPlugin()],
},
},
},
],
},
],
},
};
loaderContext
in plugin.webpack.config.js
const path = require("path");
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
"style-loader",
"css-loader",
{
loader: "postcss-loader",
options: {
postcssOptions: {
config: path.resolve(__dirname, "path/to/postcss.config.js"),
},
},
},
],
},
],
},
};
postcss.config.js
module.exports = (api) => ({
plugins: [
require("path/to/customPlugin")({
loaderContext: api.webpackLoaderContext,
}),
],
});
customPlugin.js
const path = require("path");
const customPlugin = (loaderContext) => (css, result) => {
loaderContext.webpack.addDependency(
path.resolve(__dirname, "path", "to", "file")
);
};
module.exports = postcss.plugin("postcss-assets", customPlugin);
Please take a moment to read our contributing guidelines if you haven't yet done so.
DEPREACTED for v5: please consider migrating to asset modules
.
A loader for webpack that allows importing files as a String.
To begin, you'll need to install raw-loader
:
$ npm install raw-loader --save-dev
Then add the loader to your webpack
config. For example:
file.js
import txt from './file.txt';
webpack.config.js
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.txt$/i,
use: 'raw-loader',
},
],
},
};
And run webpack
via your preferred method.
Name | Type | Default | Description |
---|---|---|---|
Name Type Default Description
|
{Boolean} |
true |
Uses ES modules syntax |
esModule
Type: Boolean
Default: true
By default, raw-loader
generates JS modules that use the ES modules syntax.
There are some cases in which using ES modules is beneficial, like in the case of module concatenation and tree shaking.
You can enable a CommonJS module syntax using:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.txt$/i,
use: [
{
loader: 'raw-loader',
options: {
esModule: false,
},
},
],
},
],
},
};
import txt from 'raw-loader!./file.txt';
Beware, if you already define loader(s) for extension(s) in webpack.config.js
you should use:
import css from '!!raw-loader!./file.txt'; // Adding `!!` to a request will disable all loaders specified in the configuration
Please take a moment to read our contributing guidelines if you haven't yet done so.
Wraps a react component in a proxy component to enable Code Splitting, which loads a react component and its dependencies on demand.
This module requires a minimum of Node v6.9.0 and Webpack v4.0.0.
To begin, you'll need to install react-proxy-loader
:
$ npm install react-proxy-loader --save-dev
Then add the loader to your webpack
config. For example:
// returns the proxied component, loaded on demand
// webpack creates an additional chunk for this component and its dependencies
const Component = require('react-proxy-loader!./Component');
// returns a mixin for the proxied component
// This allows you to setup rendering for the loading state for the proxy
const ComponentProxyMixin = require('react-proxy-loader!./Component').Mixin;
const ComponentProxy = React.createClass({
mixins: [ComponentProxyMixin],
renderUnavailable: function() {
return <p>Loading...</p>;
}
});
Or specify the proxied components in your configuration:
// webpack.config.js
module.exports = {
module: {
loaders: [
/* ... */
{
test: [
/component\.jsx$/, // select component by RegExp
/\.async\.jsx$/, // select component by extension
"/abs/path/to/component.jsx" // absolute path to component
],
loader: "react-proxy-loader"
}
]
}
};
Or provide a chunk name within a name
query parameter:
var Component = require("react-proxy-loader?name=chunkName!./Component");
And run webpack
via your preferred method.
Updates style <link>
href value with a hash to trigger a style reload
Loader new home: restyle-loader
npm install --save-dev restyle-loader
webpack.config.js
{
test: /\.css?$/,
use: [
{
loader: "restyle-loader"
},
{
loader: "file-loader",
options: {
name: "[name].css?[hash:8]"
}
}
]
}
Hash is required to enable HMR
bundle.js
require("./index.css");
// Bundle code here...
index.html
<head>
<link rel="stylesheet" type="text/css" href="css/index.css">
</head>
after the loader runs it becomes
<head>
<link rel="stylesheet" type="text/css" href="css/index.css?531fdfd0">
</head>
Daniel Verejan |
Loads a Sass/SCSS file and compiles it to CSS.
To begin, you'll need to install sass-loader
:
npm install sass-loader sass webpack --save-dev
sass-loader
requires you to install either Dart Sass or Node Sass on your own (more documentation can be found below).
This allows you to control the versions of all your dependencies, and to choose which Sass implementation to use.
ℹ️ We highly recommend using Dart Sass.
⚠ Node Sass does not work with Yarn PnP feature and doesn't support @use rule.
Chain the sass-loader
with the css-loader and the style-loader to immediately apply all styles to the DOM or the mini-css-extract-plugin to extract it into a separate file.
Then add the loader to your Webpack configuration. For example:
app.js
import "./style.scss";
style.scss
$body-color: red;
body {
color: $body-color;
}
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
"style-loader",
// Translates CSS into CommonJS
"css-loader",
// Compiles Sass to CSS
"sass-loader",
],
},
],
},
};
Finally run webpack
via your preferred method.
import
at-rulesWebpack provides an advanced mechanism to resolve files.
The sass-loader
uses Sass's custom importer feature to pass all queries to the Webpack resolving engine.
Thus you can import your Sass modules from node_modules
.
@import "bootstrap";
Using ~
is deprecated and can be removed from your code (we recommend it), but we still support it for historical reasons.
Why can you remove it? The loader will first try to resolve @import
as a relative path. If it cannot be resolved, then the loader will try to resolve @import
inside node_modules
.
Prepending module paths with a ~
tells webpack to search through node_modules
.
@import "~bootstrap";
It's important to prepend it with only ~
, because ~/
resolves to the home directory.
Webpack needs to distinguish between bootstrap
and ~bootstrap
because CSS and Sass files have no special syntax for importing relative files.
Writing @import "style.scss"
is the same as @import "./style.scss";
url(...)
Since Sass implementations don't provide url rewriting, all linked assets must be relative to the output.
css-loader
, all urls must be relative to the entry-file (e.g. main.scss
).css-loader
, it must be relative to your web root.You will be disrupted by this first issue. It is natural to expect relative references to be resolved against the .sass
/.scss
file in which they are specified (like in regular .css
files).
Thankfully there are a two solutions to this problem:
sass-loader
in the loader chain.$icon-font-path
.Name | Type | Default | Description |
---|---|---|---|
Name Type Default Description
|
{Object\|String} |
sass |
Setup Sass implementation to use. |
Name Type Default Description
|
{Object\|Function} |
defaults values for Sass implementation | Options for Sass. |
Name Type Default Description
|
{Boolean} |
compiler.devtool |
Enables/Disables generation of source maps. |
Name Type Default Description
|
{String\|Function} |
undefined |
Prepends/Appends
Sass
/
SCSS
code before the actual entry file. |
Name Type Default Description
|
{Boolean} |
true |
Enables/Disables the default Webpack importer. |
Name Type Default Description
|
{Boolean} |
false |
Treats the
@warn
rule as a webpack warning. |
implementation
Type: Object | String
Default: sass
The special implementation
option determines which implementation of Sass to use.
By default the loader resolve the implementation based on your dependencies.
Just add required implementation to package.json
(sass
or node-sass
package) and install dependencies.
Example where the sass-loader
loader uses the sass
(dart-sass
) implementation:
package.json
{
"devDependencies": {
"sass-loader": "^7.2.0",
"sass": "^1.22.10"
}
}
Example where the sass-loader
loader uses the node-sass
implementation:
package.json
{
"devDependencies": {
"sass-loader": "^7.2.0",
"node-sass": "^5.0.0"
}
}
Beware the situation when node-sass
and sass
were installed! By default the sass-loader
prefers sass
.
In order to avoid this situation you can use the implementation
option.
The implementation
options either accepts sass
(Dart Sass
) or node-sass
as a module.
For example, to use Dart Sass, you'd pass:
module.exports = {
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
"style-loader",
"css-loader",
{
loader: "sass-loader",
options: {
// Prefer `dart-sass`
implementation: require("sass"),
},
},
],
},
],
},
};
For example, to use Dart Sass, you'd pass:
module.exports = {
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
"style-loader",
"css-loader",
{
loader: "sass-loader",
options: {
// Prefer `dart-sass`
implementation: require.resolve("sass"),
},
},
],
},
],
},
};
Note that when using sass
(Dart Sass
), synchronous compilation is twice as fast as asynchronous compilation by default, due to the overhead of asynchronous callbacks.
To avoid this overhead, you can use the fibers package to call asynchronous importers from the synchronous code path.
We automatically inject the fibers
package (setup sassOptions.fiber
) for Node.js
less v16.0.0 if is possible (i.e. you need install the fibers
package).
Fibers is not compatible with
Node.js
v16.0.0 or later (see introduction to readme).
package.json
{
"devDependencies": {
"sass-loader": "^7.2.0",
"sass": "^1.22.10",
"fibers": "^4.0.1"
}
}
You can disable automatically injecting the fibers
package by passing a false
value for the sassOptions.fiber
option.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
"style-loader",
"css-loader",
{
loader: "sass-loader",
options: {
implementation: require("sass"),
sassOptions: {
fiber: false,
},
},
},
],
},
],
},
};
You can also pass the fiber
value using this code:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
"style-loader",
"css-loader",
{
loader: "sass-loader",
options: {
implementation: require("sass"),
sassOptions: {
fiber: require("fibers"),
},
},
},
],
},
],
},
};
sassOptions
Type: Object|Function
Default: defaults values for Sass implementation
Options for Dart Sass or Node Sass implementation.
ℹ️ The
charset
option hastrue
value by default fordart-sass
, we strongly discourage change value tofalse
, because webpack doesn't support files other thanutf-8
.ℹ️ The
indentedSyntax
option hastrue
value for thesass
extension.ℹ️ Options such as
data
andfile
are unavailable and will be ignored.ℹ We strongly discourage change
outFile
,sourceMapContents
,sourceMapEmbed
,sourceMapRoot
options becausesass-loader
automatically sets these options when thesourceMap
option istrue
.ℹ️ Access to the loader context inside the custom importer can be done using the
this.webpackLoaderContext
property.
There is a slight difference between the sass
(dart-sass
) and node-sass
options.
Please consult documentation before using them:
sass
options.node-sass
options.Object
Use and object for the Sass implementation setup.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
"style-loader",
"css-loader",
{
loader: "sass-loader",
options: {
sassOptions: {
indentWidth: 4,
includePaths: ["absolute/path/a", "absolute/path/b"],
},
},
},
],
},
],
},
};
Function
Allows to setup the Sass implementation by setting different options based on the loader context.
module.exports = {
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
"style-loader",
"css-loader",
{
loader: "sass-loader",
options: {
sassOptions: (loaderContext) => {
// More information about available properties https://webpack.js.org/api/loaders/
const { resourcePath, rootContext } = loaderContext;
const relativePath = path.relative(rootContext, resourcePath);
if (relativePath === "styles/foo.scss") {
return {
includePaths: ["absolute/path/c", "absolute/path/d"],
};
}
return {
includePaths: ["absolute/path/a", "absolute/path/b"],
};
},
},
},
],
},
],
},
};
sourceMap
Type: Boolean
Default: depends on the compiler.devtool
value
Enables/Disables generation of source maps.
By default generation of source maps depends on the devtool
option.
All values enable source map generation except eval
and false
value.
ℹ If a
true
thesourceMap
,sourceMapRoot
,sourceMapEmbed
,sourceMapContents
andomitSourceMapUrl
fromsassOptions
will be ignored.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
"style-loader",
{
loader: "css-loader",
options: {
sourceMap: true,
},
},
{
loader: "sass-loader",
options: {
sourceMap: true,
},
},
],
},
],
},
};
ℹ In some rare cases
node-sass
can output invalid source maps (it is anode-sass
bug).In order to avoid this, you can try to update
node-sass
to latest version or you can try to set withinsassOptions
theoutputStyle
option tocompressed
.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
"style-loader",
"css-loader",
{
loader: "sass-loader",
options: {
sourceMap: true,
sassOptions: {
outputStyle: "compressed",
},
},
},
],
},
],
},
};
additionalData
Type: String|Function
Default: undefined
Prepends Sass
/SCSS
code before the actual entry file.
In this case, the sass-loader
will not override the data
option but just prepend the entry's content.
This is especially useful when some of your Sass variables depend on the environment:
String
module.exports = {
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
"style-loader",
"css-loader",
{
loader: "sass-loader",
options: {
additionalData: "$env: " + process.env.NODE_ENV + ";",
},
},
],
},
],
},
};
Function
module.exports = {
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
"style-loader",
"css-loader",
{
loader: "sass-loader",
options: {
additionalData: (content, loaderContext) => {
// More information about available properties https://webpack.js.org/api/loaders/
const { resourcePath, rootContext } = loaderContext;
const relativePath = path.relative(rootContext, resourcePath);
if (relativePath === "styles/foo.scss") {
return "$value: 100px;" + content;
}
return "$value: 200px;" + content;
},
},
},
],
},
],
},
};
module.exports = {
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
"style-loader",
"css-loader",
{
loader: "sass-loader",
options: {
additionalData: async (content, loaderContext) => {
// More information about available properties https://webpack.js.org/api/loaders/
const { resourcePath, rootContext } = loaderContext;
const relativePath = path.relative(rootContext, resourcePath);
if (relativePath === "styles/foo.scss") {
return "$value: 100px;" + content;
}
return "$value: 200px;" + content;
},
},
},
],
},
],
},
};
webpackImporter
Type: Boolean
Default: true
Enables/Disables the default Webpack importer.
This can improve performance in some cases. Use it with caution because aliases and @import
at-rules starting with ~
will not work.
You can pass own importer
to solve this (see importer docs
).
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
"style-loader",
"css-loader",
{
loader: "sass-loader",
options: {
webpackImporter: false,
},
},
],
},
],
},
};
warnRuleAsWarning
Type: Boolean
Default: false
Treats the @warn
rule as a webpack warning.
ℹ️ It will be
true
by default in the next major release.
style.scss
$known-prefixes: webkit, moz, ms, o;
@mixin prefix($property, $value, $prefixes) {
@each $prefix in $prefixes {
@if not index($known-prefixes, $prefix) {
@warn "Unknown prefix #{$prefix}.";
}
-#{$prefix}-#{$property}: $value;
}
#{$property}: $value;
}
.tilt {
// Oops, we typo'd "webkit" as "wekbit"!
@include prefix(transform, rotate(15deg), wekbit ms);
}
The presented code will throw webpack warning instead logging.
To ignore unnecessary warnings you can use the ignoreWarnings option.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
"style-loader",
"css-loader",
{
loader: "sass-loader",
options: {
warnRuleAsWarning: true,
},
},
],
},
],
},
};
For production builds it's recommended to extract the CSS from your bundle being able to use parallel loading of CSS/JS resources later on.
There are two possibilities to extract a style sheet from the bundle:
webpack.config.js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// fallback to style-loader in development
process.env.NODE_ENV !== "production"
? "style-loader"
: MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader",
],
},
],
},
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: "[name].css",
chunkFilename: "[id].css",
}),
],
};
Enables/Disables generation of source maps.
To enable CSS source maps, you'll need to pass the sourceMap
option to the sass-loader
and the css-loader.
webpack.config.js
module.exports = {
devtool: "source-map", // any "source-map"-like devtool is possible
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
"style-loader",
{
loader: "css-loader",
options: {
sourceMap: true,
},
},
{
loader: "sass-loader",
options: {
sourceMap: true,
},
},
],
},
],
},
};
If you want to edit the original Sass files inside Chrome, there's a good blog post. Checkout test/sourceMap for a running example.
Please take a moment to read our contributing guidelines if you haven't yet done so.
npm install --save-dev script-loader
Executes JS script once in global context.
:warning: Doesn't work in NodeJS
import './script.exec.js';
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.exec\.js$/,
use: [ 'script-loader' ]
}
]
}
}
import 'script-loader!./script.js';
Name | Type | Default | Description |
---|---|---|---|
Name Type Default Description
|
{Boolean} |
false |
Enable/Disable Sourcemaps |
Name Type Default Description
|
{Boolean} |
true |
Enable/Disable useStrict |
sourceMap
Type: Boolean
Default: false
To include source maps set the sourceMap
option.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.script\.js$/,
use: [
{
loader: 'script-loader',
options: {
sourceMap: true,
},
},
]
}
]
}
}
useStrict
Type: Boolean
Default: true
To disable use strict set the useStrict
option to false
.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.script\.js$/,
use: [
{
loader: 'script-loader',
options: {
useStrict: false,
},
},
]
}
]
}
}
Juho Vepsäläinen | Joshua Wiens | Kees Kluskens | Sean Larkin |
Extracts source maps from existing source files (from their sourceMappingURL
).
To begin, you'll need to install source-map-loader
:
npm i -D source-map-loader
Then add the plugin to your webpack
config. For example:
file.js
import css from "file.css";
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.js$/,
enforce: "pre",
use: ["source-map-loader"],
},
],
},
};
The source-map-loader
extracts existing source maps from all JavaScript entries.
This includes both inline source maps as well as those linked via URL.
All source map data is passed to webpack for processing as per a chosen source map style specified by the devtool
option in webpack.config.js.
This loader is especially useful when using 3rd-party libraries having their own source maps.
If not extracted and processed into the source map of the webpack bundle, browsers may misinterpret source map data. source-map-loader
allows webpack to maintain source map data continuity across libraries so ease of debugging is preserved.
The source-map-loader
will extract from any JavaScript file, including those in the node_modules
directory.
Be mindful in setting include and exclude rule conditions to maximize bundling performance.
And run webpack
via your preferred method.
Name | Type | Default | Description |
---|---|---|---|
Name Type Default Description
|
{Function} |
undefined |
Allows to control
SourceMappingURL
behaviour |
Type: Function
Default: undefined
Allows you to specify the behavior of the loader for SourceMappingURL
comment.
The function must return one of the values:
true
or 'consume'
- consume the source map and remove SourceMappingURL
comment (default behavior)false
or 'remove'
- do not consume the source map and remove SourceMappingURL
commentskip
- do not consume the source map and do not remove SourceMappingURL
commentExample configuration:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.js$/,
enforce: "pre",
use: [
{
loader: "source-map-loader",
options: {
filterSourceMappingUrl: (url, resourcePath) => {
if (/broker-source-map-url\.js$/i.test(url)) {
return false;
}
if (/keep-source-mapping-url\.js$/i.test(resourcePath)) {
return "skip";
}
return true;
},
},
},
],
},
],
},
};
To ignore warnings, you can use the following configuration:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.js$/,
enforce: "pre",
use: ["source-map-loader"],
},
],
},
ignoreWarnings: [/Failed to parse source map/],
};
More information about the ignoreWarnings
option can be found here
Please take a moment to read our contributing guidelines if you haven't yet done so.
Inject CSS into the DOM.
To begin, you'll need to install style-loader
:
npm install --save-dev style-loader
It's recommended to combine style-loader
with the css-loader
Then add the loader to your webpack
config. For example:
style.css
body {
background: green;
}
component.js
import "./style.css";
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
],
},
};
Name | Type | Default | Description |
---|---|---|---|
Name Type Default Description
|
{String} |
styleTag |
Allows to setup how styles will be injected into the DOM |
Name Type Default Description
|
{Object} |
{} |
Adds custom attributes to tag |
Name Type Default Description
|
{String\|Function} |
head |
Inserts tag at the given position into the DOM |
Name Type Default Description
|
{String\|Function} |
undefined |
Transform tag and css when insert 'style' tag into the DOM |
Name Type Default Description
|
{Number} |
true |
Sets module ID base (DLLPlugin) |
Name Type Default Description
|
{Boolean} |
true |
Use ES modules syntax |
injectType
Type: String
Default: styleTag
Allows to setup how styles will be injected into the DOM.
Possible values:
styleTag
singletonStyleTag
autoStyleTag
lazyStyleTag
lazySingletonStyleTag
lazyAutoStyleTag
linkTag
styleTag
Automatically injects styles into the DOM using multiple <style></style>
. It is default behaviour.
component.js
import "./styles.css";
Example with Locals (CSS Modules):
component-with-css-modules.js
import styles from "./styles.css";
const divElement = document.createElement("div");
divElement.className = styles["my-class"];
All locals (class names) stored in imported object.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
// The `injectType` option can be avoided because it is default behaviour
{ loader: "style-loader", options: { injectType: "styleTag" } },
"css-loader",
],
},
],
},
};
The loader inject styles like:
<style>
.foo {
color: red;
}
</style>
<style>
.bar {
color: blue;
}
</style>
singletonStyleTag
Automatically injects styles into the DOM using one <style></style>
.
⚠ Source maps do not work.
component.js
import "./styles.css";
component-with-css-modules.js
import styles from "./styles.css";
const divElement = document.createElement("div");
divElement.className = styles["my-class"];
All locals (class names) stored in imported object.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
{
loader: "style-loader",
options: { injectType: "singletonStyleTag" },
},
"css-loader",
],
},
],
},
};
The loader inject styles like:
<style>
.foo {
color: red;
}
.bar {
color: blue;
}
</style>
autoStyleTag
Works the same as a styleTag
, but if the code is executed in IE6-9, turns on the singletonStyleTag
mode.
lazyStyleTag
Injects styles into the DOM using multiple <style></style>
on demand.
We recommend following .lazy.css
naming convention for lazy styles and the .css
for basic style-loader
usage (similar to other file types, i.e. .lazy.less
and .less
).
When you lazyStyleTag
value the style-loader
injects the styles lazily making them useable on-demand via style.use()
/ style.unuse()
.
⚠️ Behavior is undefined when
unuse
is called more often thanuse
. Don't do that.
component.js
import styles from "./styles.lazy.css";
styles.use();
// For removing styles you can use
// styles.unuse();
component-with-css-modules.js
import styles from "./styles.lazy.css";
styles.use();
const divElement = document.createElement("div");
divElement.className = styles.locals["my-class"];
All locals (class names) stored in locals
property of imported object.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
exclude: /\.lazy\.css$/i,
use: ["style-loader", "css-loader"],
},
{
test: /\.lazy\.css$/i,
use: [
{ loader: "style-loader", options: { injectType: "lazyStyleTag" } },
"css-loader",
],
},
],
},
};
The loader inject styles like:
<style>
.foo {
color: red;
}
</style>
<style>
.bar {
color: blue;
}
</style>
lazySingletonStyleTag
Injects styles into the DOM using one <style></style>
on demand.
We recommend following .lazy.css
naming convention for lazy styles and the .css
for basic style-loader
usage (similar to other file types, i.e. .lazy.less
and .less
).
When you lazySingletonStyleTag
value the style-loader
injects the styles lazily making them useable on-demand via style.use()
/ style.unuse()
.
⚠️ Source maps do not work.
⚠️ Behavior is undefined when
unuse
is called more often thanuse
. Don't do that.
component.js
import styles from "./styles.css";
styles.use();
// For removing styles you can use
// styles.unuse();
component-with-css-modules.js
import styles from "./styles.lazy.css";
styles.use();
const divElement = document.createElement("div");
divElement.className = styles.locals["my-class"];
All locals (class names) stored in locals
property of imported object.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
exclude: /\.lazy\.css$/i,
use: ["style-loader", "css-loader"],
},
{
test: /\.lazy\.css$/i,
use: [
{
loader: "style-loader",
options: { injectType: "lazySingletonStyleTag" },
},
"css-loader",
],
},
],
},
};
The loader generate this:
<style>
.foo {
color: red;
}
.bar {
color: blue;
}
</style>
lazyAutoStyleTag
Works the same as a lazyStyleTag
, but if the code is executed in IE6-9, turns on the lazySingletonStyleTag
mode.
linkTag
Injects styles into the DOM using multiple <link rel="stylesheet" href="path/to/file.css">
.
ℹ️ The loader will dynamically insert the
<link href="path/to/file.css" rel="stylesheet">
tag at runtime via JavaScript. You should use MiniCssExtractPlugin if you want to include a static<link href="path/to/file.css" rel="stylesheet">
.
import "./styles.css";
import "./other-styles.css";
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.link\.css$/i,
use: [
{ loader: "style-loader", options: { injectType: "linkTag" } },
{ loader: "file-loader" },
],
},
],
},
};
The loader generate this:
<link rel="stylesheet" href="path/to/style.css" />
<link rel="stylesheet" href="path/to/other-styles.css" />
attributes
Type: Object
Default: {}
If defined, the style-loader
will attach given attributes with their values on <style>
/ <link>
element.
component.js
import style from "./file.css";
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
{ loader: "style-loader", options: { attributes: { id: "id" } } },
{ loader: "css-loader" },
],
},
],
},
};
<style id="id"></style>
insert
Type: String|Function
Default: head
By default, the style-loader
appends <style>
/<link>
elements to the end of the style target, which is the <head>
tag of the page unless specified by insert
.
This will cause CSS created by the loader to take priority over CSS already present in the target.
You can use other values if the standard behavior is not suitable for you, but we do not recommend doing this.
If you target an iframe make sure you have sufficient access rights, the styles will be injected into the content document head.
String
Selector
Allows to setup custom query selector where styles inject into the DOM.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
{
loader: "style-loader",
options: {
insert: "body",
},
},
"css-loader",
],
},
],
},
};
Absolute path to function
Allows to setup absolute path to custom function that allows to override default behavior and insert styles at any position.
⚠ Do not forget that this code will be used in the browser and not all browsers support latest ECMA features like
let
,const
,arrow function expression
and etc. We recommend usingbabel-loader
for support latest ECMA features. ⚠ Do not forget that some DOM methods may not be available in older browsers, we recommended use only DOM core level 2 properties, but it is depends what browsers you want to support
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
{
loader: "style-loader",
options: {
insert: require.resolve("modulePath"),
},
},
"css-loader",
],
},
],
},
};
A new <style>
/<link>
elements will be inserted into at bottom of body
tag.
Function
Allows to override default behavior and insert styles at any position.
⚠ Do not forget that this code will be used in the browser and not all browsers support latest ECMA features like
let
,const
,arrow function expression
and etc, we recommend use only ECMA 5 features, but it is depends what browsers you want to support ⚠ Do not forget that some DOM methods may not be available in older browsers, we recommended use only DOM core level 2 properties, but it is depends what browsers you want to support
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
{
loader: "style-loader",
options: {
insert: function insertAtTop(element) {
var parent = document.querySelector("head");
// eslint-disable-next-line no-underscore-dangle
var lastInsertedElement =
window._lastElementInsertedByStyleLoader;
if (!lastInsertedElement) {
parent.insertBefore(element, parent.firstChild);
} else if (lastInsertedElement.nextSibling) {
parent.insertBefore(element, lastInsertedElement.nextSibling);
} else {
parent.appendChild(element);
}
// eslint-disable-next-line no-underscore-dangle
window._lastElementInsertedByStyleLoader = element;
},
},
},
"css-loader",
],
},
],
},
};
Insert styles at top of head
tag.
You can pass any parameters to style.use(options)
and this value will be passed to insert
and styleTagTransform
functions.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
{
loader: "style-loader",
options: {
injectType: "lazyStyleTag",
// Do not forget that this code will be used in the browser and
// not all browsers support latest ECMA features like `let`, `const`, `arrow function expression` and etc,
// we recommend use only ECMA 5 features,
// but it is depends what browsers you want to support
insert: function insertIntoTarget(element, options) {
var parent = options.target || document.head;
parent.appendChild(element);
},
},
},
"css-loader",
],
},
],
},
};
Insert styles to the provided element or to the head
tag if target isn't provided. Now you can inject styles into Shadow DOM (or any other element).
custom-square.css
div {
width: 50px;
height: 50px;
background-color: red;
}
custom-square.js
import customSquareStyles from "./custom-square.css";
class CustomSquare extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
const divElement = document.createElement("div");
divElement.textContent = "Text content.";
this.shadowRoot.appendChild(divElement);
customSquareStyles.use({ target: this.shadowRoot });
// You can override injected styles
const bgPurple = new CSSStyleSheet();
const width = this.getAttribute("w");
const height = this.getAttribute("h");
bgPurple.replace(`div { width: ${width}px; height: ${height}px; }`);
this.shadowRoot.adoptedStyleSheets = [bgPurple];
// `divElement` will have `100px` width, `100px` height and `red` background color
}
}
customElements.define("custom-square", CustomSquare);
export default CustomSquare;
styleTagTransform
Type: String | Function
Default: undefined
String
Allows to setup absolute path to custom function that allows to override default behavior styleTagTransform.
⚠ Do not forget that this code will be used in the browser and not all browsers support latest ECMA features like
let
,const
,arrow function expression
and etc, we recommend use only ECMA 5 features, but it is depends what browsers you want to support
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
{
loader: "style-loader",
options: {
injectType: "styleTag",
styleTagTransform: require.resolve("module-path"),
},
},
"css-loader",
],
},
],
},
};
Function
Transform tag and css when insert 'style' tag into the DOM.
⚠ Do not forget that this code will be used in the browser and not all browsers support latest ECMA features like
let
,const
,arrow function expression
and etc, we recommend use only ECMA 5 features, but it is depends what browsers you want to support ⚠ Do not forget that some DOM methods may not be available in older browsers, we recommended use only DOM core level 2 properties, but it is depends what browsers you want to support
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
{
loader: "style-loader",
options: {
injectType: "styleTag",
styleTagTransform: function (css, style) {
// Do something ...
style.innerHTML = `${css}.modify{}\n`;
document.head.appendChild(style);
},
},
},
"css-loader",
],
},
],
},
};
base
This setting is primarily used as a workaround for css clashes when using one or more DllPlugin's. base
allows you to prevent either the app's css (or DllPlugin2's css) from overwriting DllPlugin1's css by specifying a css module id base which is greater than the range used by DllPlugin1 e.g.:
webpack.dll1.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
],
},
};
webpack.dll2.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
{ loader: "style-loader", options: { base: 1000 } },
"css-loader",
],
},
],
},
};
webpack.app.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
{ loader: "style-loader", options: { base: 2000 } },
"css-loader",
],
},
],
},
};
esModule
Type: Boolean
Default: true
By default, style-loader
generates JS modules that use the ES modules syntax.
There are some cases in which using ES modules is beneficial, like in the case of module concatenation and tree shaking.
You can enable a CommonJS modules syntax using:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: "style-loader",
options: {
esModule: false,
},
},
],
},
};
For production
builds it's recommended to extract the CSS from your bundle being able to use parallel loading of CSS/JS resources later on.
This can be achieved by using the mini-css-extract-plugin, because it creates separate css files.
For development
mode (including webpack-dev-server
) you can use style-loader
, because it injects CSS into the DOM using multiple <style></style>
and works faster.
⚠ Do not use together
style-loader
andmini-css-extract-plugin
.
webpack.config.js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const devMode = process.env.NODE_ENV !== "production";
module.exports = {
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/,
use: [
devMode ? "style-loader" : MiniCssExtractPlugin.loader,
"css-loader",
"postcss-loader",
"sass-loader",
],
},
],
},
plugins: [].concat(devMode ? [] : [new MiniCssExtractPlugin()]),
};
⚠ Names of locals are converted to
camelCase
.⚠ It is not allowed to use JavaScript reserved words in css class names.
⚠ Options
esModule
andmodules.namedExport
incss-loader
should be enabled.
styles.css
.foo-baz {
color: red;
}
.bar {
color: blue;
}
index.js
import { fooBaz, bar } from "./styles.css";
console.log(fooBaz, bar);
You can enable a ES module named export using:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: "style-loader",
},
{
loader: "css-loader",
options: {
modules: {
namedExport: true,
},
},
},
],
},
],
},
};
The loader automatically inject source maps when previous loader emit them.
Therefore, to generate source maps, set the sourceMap
option to true
for the previous loader.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
"style-loader",
{ loader: "css-loader", options: { sourceMap: true } },
],
},
],
},
};
There are two ways to work with nonce
:
attributes
option__webpack_nonce__
variable⚠ the
attributes
option takes precedence over the__webpack_nonce__
variable
attributes
component.js
import "./style.css";
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
{
loader: "style-loader",
options: {
attributes: {
nonce: "12345678",
},
},
},
"css-loader",
],
},
],
},
};
The loader generate:
<style nonce="12345678">
.foo {
color: red;
}
</style>
__webpack_nonce__
create-nonce.js
__webpack_nonce__ = "12345678";
component.js
import "./create-nonce.js";
import "./style.css";
Alternative example for require
:
component.js
__webpack_nonce__ = "12345678";
require("./style.css");
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
],
},
};
The loader generate:
<style nonce="12345678">
.foo {
color: red;
}
</style>
Inserts styles at top of head
tag.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
{
loader: "style-loader",
options: {
insert: function insertAtTop(element) {
var parent = document.querySelector("head");
var lastInsertedElement =
window._lastElementInsertedByStyleLoader;
if (!lastInsertedElement) {
parent.insertBefore(element, parent.firstChild);
} else if (lastInsertedElement.nextSibling) {
parent.insertBefore(element, lastInsertedElement.nextSibling);
} else {
parent.appendChild(element);
}
window._lastElementInsertedByStyleLoader = element;
},
},
},
"css-loader",
],
},
],
},
};
Inserts styles before #id
element.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
{
loader: "style-loader",
options: {
insert: function insertBeforeAt(element) {
const parent = document.querySelector("head");
const target = document.querySelector("#id");
const lastInsertedElement =
window._lastElementInsertedByStyleLoader;
if (!lastInsertedElement) {
parent.insertBefore(element, target);
} else if (lastInsertedElement.nextSibling) {
parent.insertBefore(element, lastInsertedElement.nextSibling);
} else {
parent.appendChild(element);
}
window._lastElementInsertedByStyleLoader = element;
},
},
},
"css-loader",
],
},
],
},
};
You can define custom target for your styles for the lazyStyleTag
type.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
{
loader: "style-loader",
options: {
injectType: "lazyStyleTag",
// Do not forget that this code will be used in the browser and
// not all browsers support latest ECMA features like `let`, `const`, `arrow function expression` and etc,
// we recommend use only ECMA 5 features,
// but it is depends what browsers you want to support
insert: function insertIntoTarget(element, options) {
var parent = options.target || document.head;
parent.appendChild(element);
},
},
},
"css-loader",
],
},
],
},
};
Insert styles to the provided element or to the head
tag if target isn't provided.
custom-square.css
div {
width: 50px;
height: 50px;
background-color: red;
}
custom-square.js
import customSquareStyles from "./custom-square.css";
class CustomSquare extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
const divElement = document.createElement("div");
divElement.textContent = "Text content.";
this.shadowRoot.appendChild(divElement);
customSquareStyles.use({ target: this.shadowRoot });
// You can override injected styles
const bgPurple = new CSSStyleSheet();
const width = this.getAttribute("w");
const height = this.getAttribute("h");
bgPurple.replace(`div { width: ${width}px; height: ${height}px; }`);
this.shadowRoot.adoptedStyleSheets = [bgPurple];
// `divElement` will have `100px` width, `100px` height and `red` background color
}
}
customElements.define("custom-square", CustomSquare);
export default CustomSquare;
Please take a moment to read our contributing guidelines if you haven't yet done so.
This Webpack loader inlines SVG as module. If you use Adobe suite or Sketch to export SVGs, you will get auto-generated, unneeded crusts. This loader removes it for you, too.
npm install svg-inline-loader --save-dev
Simply add configuration object to module.loaders
like this.
{
test: /\.svg$/,
loader: 'svg-inline-loader'
}
warning: You should configure this loader only once via module.loaders
or require('!...')
. See #15 for detail.
removeTags: boolean
Removes specified tags and its children. You can specify tags by setting removingTags
query array.
default: removeTags: false
removingTags: [...string]
warning: this won't work unless you specify removeTags: true
default: removingTags: ['title', 'desc', 'defs', 'style']
warnTags: [...string]
warns about tags, ex: ['desc', 'defs', 'style']
default: warnTags: []
removeSVGTagAttrs: boolean
Removes width
and height
attributes from <svg />
.
default: removeSVGTagAttrs: true
removingTagAttrs: [...string]
Removes attributes from inside the <svg />
.
default: removingTagAttrs: []
warnTagAttrs: [...string]
Warns to console about attributes from inside the <svg />
.
default: warnTagAttrs: []
classPrefix: boolean || string
Adds a prefix to class names to avoid collision across svg files.
default: classPrefix: false
idPrefix: boolean || string
Adds a prefix to ids to avoid collision across svg files.
default: idPrefix: false
// Using default hashed prefix (__[hash:base64:7]__)
var logoTwo = require('svg-inline-loader?classPrefix!./logo_two.svg');
// Using custom string
var logoOne = require('svg-inline-loader?classPrefix=my-prefix-!./logo_one.svg');
// Using custom string and hash
var logoThree = require('svg-inline-loader?classPrefix=__prefix-[sha512:hash:hex:5]__!./logo_three.svg');
See loader-utils for hash options.
Preferred usage is via a module.loaders
:
{
test: /\.svg$/,
loader: 'svg-inline-loader?classPrefix'
}
Juho Vepsäläinen | Joshua Wiens | Kees Kluskens | Sean Larkin |
Runs the following loaders in a worker pool.
npm install --save-dev thread-loader
Put this loader in front of other loaders. The following loaders run in a worker pool.
Loaders running in a worker pool are limited. Examples:
Each worker is a separate node.js process, which has an overhead of ~600ms. There is also an overhead of inter-process communication.
Use this loader only for expensive operations!
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.js$/,
include: path.resolve('src'),
use: [
'thread-loader',
// your expensive loader (e.g babel-loader)
],
},
],
},
};
with options
use: [
{
loader: 'thread-loader',
// loaders with equal options will share worker pools
options: {
// the number of spawned workers, defaults to (number of cpus - 1) or
// fallback to 1 when require('os').cpus() is undefined
workers: 2,
// number of jobs a worker processes in parallel
// defaults to 20
workerParallelJobs: 50,
// additional node.js arguments
workerNodeArgs: ['--max-old-space-size=1024'],
// Allow to respawn a dead worker pool
// respawning slows down the entire compilation
// and should be set to false for development
poolRespawn: false,
// timeout for killing the worker processes when idle
// defaults to 500 (ms)
// can be set to Infinity for watching builds to keep workers alive
poolTimeout: 2000,
// number of jobs the poll distributes to the workers
// defaults to 200
// decrease of less efficient but more fair distribution
poolParallelJobs: 50,
// name of the pool
// can be used to create different pools with elsewise identical options
name: 'my-pool',
},
},
// your expensive loader (e.g babel-loader)
];
prewarming
To prevent the high delay when booting workers it possible to warmup the worker pool.
This boots the max number of workers in the pool and loads specified modules into the node.js module cache.
const threadLoader = require('thread-loader');
threadLoader.warmup(
{
// pool options, like passed to loader options
// must match loader options to boot the correct pool
},
[
// modules to load
// can be any module, i. e.
'babel-loader',
'babel-preset-es2015',
'sass-loader',
]
);
Please take a moment to read our contributing guidelines if you haven't yet done so.
A browserify transformation loader for webpack.
This loader allows use of browserify transforms via a webpack loader.
To begin, you'll need to install transform-loader
:
$ npm install transform-loader --save-dev
Note: We're using the coffeeify tranform for these examples.
Then invoke the loader through a require like so:
const thing = require('!transform-loader?coffeeify!widget/thing');
Or add the loader to your webpack
config. For example:
// entry.js
import thing from 'widget/thing';
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.coffee?$/,
loader: `transform-loader?coffeeify`,
// options: {...}
},
],
},
};
And run webpack
via your preferred method.
When using the loader via a require
query string you may specify one of two
types; a loader name, or a function index.
Type: String
The name of the browserify
transform you wish to use.
Note: You must install the correct transform manually. Webpack nor this loader will do that for you.
Type: Number
The index of a function contained within options.transforms
which to use to
transform the target file(s).
transforms
Type: Array[Function]
Default: undefined
An array of functions
that can be used to transform a given file matching the
configured loader test
. For example:
// entry.js
const thing = require('widget/thing');
// webpack.config.js
const through = require('through2');
module.exports = {
module: {
rules: [
{
test: /\.ext$/,
// NOTE: we've specified an index of 0, which will use the `transform`
// function in `transforms` below.
loader: 'transform-loader?0',
options: {
transforms: [
function transform() {
return through(
(buffer) => {
const result = buffer
.split('')
.map((chunk) =>
String.fromCharCode(127 - chunk.charCodeAt(0))
);
return this.queue(result).join('');
},
() => this.queue(null)
);
},
],
},
},
],
},
};
Please take a moment to read our contributing guidelines if you haven't yet done so.
DEPREACTED for v5: please consider migrating to asset modules
.
A loader for webpack which transforms files into base64 URIs.
To begin, you'll need to install url-loader
:
$ npm install url-loader --save-dev
url-loader
works like
file-loader
, but can return
a DataURL if the file is smaller than a byte limit.
index.js
import img from './image.png';
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(png|jpg|gif)$/i,
use: [
{
loader: 'url-loader',
options: {
limit: 8192,
},
},
],
},
],
},
};
And run webpack
via your preferred method.
Name | Type | Default | Description |
---|---|---|---|
Name Type Default Description
|
{Boolean\|Number\|String} |
true |
Specifying the maximum size of a file in bytes. |
Name Type Default Description
|
{Boolean\|String} |
based from mime-types | Sets the MIME type for the file to be transformed. |
Name Type Default Description
|
{Boolean\|String} |
base64 |
Specify the encoding which the file will be inlined with. |
Name Type Default Description
|
{Function} |
() => type/subtype;encoding,base64_data |
You can create you own custom implementation for encoding data. |
Name Type Default Description
|
{String} |
file-loader |
Specifies an alternative loader to use when a target file's size exceeds the limit. |
Name Type Default Description
|
{Boolean} |
true |
Use ES modules syntax. |
limit
Type: Boolean|Number|String
Default: true
The limit can be specified via loader options and defaults to no limit.
Boolean
Enable or disable transform files into base64.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(png|jpg|gif)$/i,
use: [
{
loader: 'url-loader',
options: {
limit: false,
},
},
],
},
],
},
};
Number|String
A Number
or String
specifying the maximum size of a file in bytes.
If the file size is equal or greater than the limit file-loader
will be used (by default) and all query parameters are passed to it.
Using an alternative to file-loader
is enabled via the fallback
option.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(png|jpg|gif)$/i,
use: [
{
loader: 'url-loader',
options: {
limit: 8192,
},
},
],
},
],
},
};
mimetype
Type: Boolean|String
Default: based from mime-types
Specify the mimetype
which the file will be inlined with.
If unspecified the mimetype
value will be used from mime-types.
Boolean
The true
value allows to generation the mimetype
part from mime-types.
The false
value removes the mediatype
part from a Data URL (if omitted, defaults to text/plain;charset=US-ASCII
).
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(png|jpg|gif)$/i,
use: [
{
loader: 'url-loader',
options: {
mimetype: false,
},
},
],
},
],
},
};
String
Sets the MIME type for the file to be transformed.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(png|jpg|gif)$/i,
use: [
{
loader: 'url-loader',
options: {
mimetype: 'image/png',
},
},
],
},
],
},
};
encoding
Type: Boolean|String
Default: base64
Specify the encoding
which the file will be inlined with.
If unspecified the encoding
will be base64
.
Boolean
If you don't want to use any encoding you can set encoding
to false
however if you set it to true
it will use the default encoding base64
.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.svg$/i,
use: [
{
loader: 'url-loader',
options: {
encoding: false,
},
},
],
},
],
},
};
String
It supports Node.js Buffers and Character Encodings which are ["utf8","utf16le","latin1","base64","hex","ascii","binary","ucs2"]
.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.svg$/i,
use: [
{
loader: 'url-loader',
options: {
encoding: 'utf8',
},
},
],
},
],
},
};
generator
Type: Function
Default: (mimetype, encoding, content, resourcePath) => mimetype;encoding,base64_content
You can create you own custom implementation for encoding data.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(png|html)$/i,
use: [
{
loader: 'url-loader',
options: {
// The `mimetype` and `encoding` arguments will be obtained from your options
// The `resourcePath` argument is path to file.
generator: (content, mimetype, encoding, resourcePath) => {
if (/\.html$/i.test(resourcePath)) {
return `data:${mimetype},${content.toString()}`;
}
return `data:${mimetype}${
encoding ? `;${encoding}` : ''
},${content.toString(encoding)}`;
},
},
},
],
},
],
},
};
fallback
Type: String
Default: 'file-loader'
Specifies an alternative loader to use when a target file's size exceeds the limit set in the limit
option.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(png|jpg|gif)$/i,
use: [
{
loader: 'url-loader',
options: {
fallback: require.resolve('responsive-loader'),
},
},
],
},
],
},
};
The fallback loader will receive the same configuration options as url-loader.
For example, to set the quality option of a responsive-loader above use:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(png|jpg|gif)$/i,
use: [
{
loader: 'url-loader',
options: {
fallback: require.resolve('responsive-loader'),
quality: 85,
},
},
],
},
],
},
};
esModule
Type: Boolean
Default: true
By default, file-loader
generates JS modules that use the ES modules syntax.
There are some cases in which using ES modules is beneficial, like in the case of module concatenation and tree shaking.
You can enable a CommonJS module syntax using:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: 'url-loader',
options: {
esModule: false,
},
},
],
},
],
},
};
SVG can be compressed into a more compact output, avoiding base64
.
You can read about it more here.
You can do it using mini-svg-data-uri package.
webpack.config.js
const svgToMiniDataURI = require('mini-svg-data-uri');
module.exports = {
module: {
rules: [
{
test: /\.svg$/i,
use: [
{
loader: 'url-loader',
options: {
generator: (content) => svgToMiniDataURI(content.toString()),
},
},
],
},
],
},
};
Please take a moment to read our contributing guidelines if you haven't yet done so.
A webpack loader which executes a given module, and returns the result of the execution at build-time, when the module is required in the bundle. In this way, the loader changes a module from code to a result.
Another way to view val-loader
, is that it allows a user a way to make their
own custom loader logic, without having to write a custom loader.
The target module is called with two arguments: (options, loaderContext)
options
: The loader options (for instance provided in the webpack config. See the example below).loaderContext
: The loader context.To begin, you'll need to install val-loader
:
$ npm install val-loader --save-dev
Then add the loader to your webpack
config. For example:
target-file.js
module.exports = (options, loaderContext) => {
return { code: "module.exports = 42;" };
};
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /target-file.js$/,
use: [
{
loader: `val-loader`,
},
],
},
],
},
};
src/entry.js
const answer = require("target-file");
And run webpack
via your preferred method.
Name | Type | Default | Description |
---|---|---|---|
Name Type Default Description
|
{String} |
undefined |
Allows to specify path to the executable file |
Type: String
Default: undefined
Allows to specify path to the executable file
data.json
{
"years": "10"
}
executable-file.js
module.exports = function yearsInMs(options, loaderContext, content) {
const { years } = JSON.parse(content);
const value = years * 365 * 24 * 60 * 60 * 1000;
return {
cacheable: true,
code: "module.exports = " + value,
};
};
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.(json)$/i,
rules: [
{
loader: "val-loader",
options: {
executableFile: path.resolve(
__dirname,
"fixtures",
"executableFile.js"
),
},
},
],
},
{
test: /\.json$/i,
type: "asset/resource",
},
],
},
};
Targeted modules of this loader must export a Function
that returns an object,
or a Promise
resolving an object (e.g. async function), containing a code
property at a minimum, but can
contain any number of additional properties.
code
Type: String|Buffer
Default: undefined
Required
Code passed along to webpack or the next loader that will replace the module.
sourceMap
Type: Object
Default: undefined
A source map passed along to webpack or the next loader.
ast
Type: Array[Object]
Default: undefined
An Abstract Syntax Tree that will be passed to the next loader. Useful to speed up the build time if the next loader uses the same AST.
dependencies
Type: Array[String]
Default: []
An array of absolute, native paths to file dependencies that should be watched by webpack for changes.
Dependencies can also be added using loaderContext.addDependency(file: string)
.
contextDependencies
Type: Array[String]
Default: []
An array of absolute, native paths to directory dependencies that should be watched by webpack for changes.
Context dependencies can also be added using loaderContext.addContextDependency(directory: string)
.
buildDependencies
Type: Array[String]
Default: []
An array of absolute, native paths to directory dependencies that should be watched by webpack for changes.
Build dependencies can also be added using loaderContext.addBuildDependency(file: string)
.
cacheable
Type: Boolean
Default: false
If true
, specifies that the code can be re-used in watch mode if none of the
dependencies
have changed.
In this example the loader is configured to operator on a file name of
years-in-ms.js
, execute the code, and store the result in the bundle as the
result of the execution. This example passes years
as an option
, which
corresponds to the years
parameter in the target module exported function:
years-in-ms.js
module.exports = function yearsInMs({ years }) {
const value = years * 365 * 24 * 60 * 60 * 1000;
// NOTE: this return value will replace the module in the bundle
return {
cacheable: true,
code: "module.exports = " + value,
};
};
webpack.config.js
module.exports = {
module: {
rules: [
{
test: require.resolve("src/years-in-ms.js"),
use: [
{
loader: "val-loader",
options: {
years: 10,
},
},
],
},
],
},
};
In the bundle, requiring the module then returns:
import tenYearsMs from "years-in-ms";
console.log(tenYearsMs); // 315360000000
Example shows how to build modernizr
.
entry.js
import modenizr from "./modernizr.js";
modernizr.js
const modernizr = require("modernizr");
module.exports = function (options) {
return new Promise(function (resolve) {
// It is impossible to throw an error because modernizr causes the process.exit(1)
modernizr.build(options, function (output) {
resolve({
cacheable: true,
code: `var modernizr; var hadGlobal = 'Modernizr' in window; var oldGlobal = window.Modernizr; ${output} modernizr = window.Modernizr; if (hadGlobal) { window.Modernizr = oldGlobal; } else { delete window.Modernizr; } export default modernizr;`,
});
});
});
};
webpack.config.js
const path = require("path");
module.exports = {
module: {
rules: [
{
test: path.resolve(__dirname, "src", "modernizr.js"),
use: [
{
loader: "val-loader",
options: {
minify: false,
options: ["setClasses"],
"feature-detects": [
"test/css/flexbox",
"test/es6/promises",
"test/serviceworker",
],
},
},
],
},
],
},
};
Example shows how to build figlet
.
entry.js
import { default as figlet } from "./figlet.js";
console.log(figlet);
figlet.js
const figlet = require("figlet");
function wrapOutput(output, config) {
let figletOutput = "";
if (config.textBefore) {
figletOutput += encodeURI(`${config.textBefore}\n`);
}
output.split("\n").forEach((line) => {
figletOutput += encodeURI(`${line}\n`);
});
if (config.textAfter) {
figletOutput += encodeURI(`${config.textAfter}\n`);
}
return `module.exports = decodeURI("${figletOutput}");`;
}
module.exports = function (options) {
const defaultConfig = {
fontOptions: {
font: "ANSI Shadow",
horizontalLayout: "default",
kerning: "default",
verticalLayout: "default",
},
text: "FIGLET-LOADER",
textAfter: null,
textBefore: null,
};
const config = Object.assign({}, defaultConfig, options);
return new Promise(function (resolve, reject) {
figlet.text(config.text, config.fontOptions, (error, output) => {
if (error) {
return reject(error);
}
resolve({
cacheable: true,
code: "module.exports = " + wrapOutput(output, config),
});
});
});
};
webpack.config.js
const path = require("path");
module.exports = {
module: {
rules: [
{
test: path.resolve(__dirname, "src", "figlet.js"),
use: [
{
loader: "val-loader",
options: {
text: "FIGLET",
},
},
],
},
],
},
};
Please take a moment to read our contributing guidelines if you haven't yet done so.
DEPRECATED for v5: https://webpack.js.org/guides/web-workers/
Web Worker loader for webpack 4.
Note that this is specific to webpack 4. To use Web Workers in webpack 5, see https://webpack.js.org/guides/web-workers/.
To begin, you'll need to install worker-loader
:
$ npm install worker-loader --save-dev
App.js
import Worker from "worker-loader!./Worker.js";
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.worker\.js$/,
use: { loader: "worker-loader" },
},
],
},
};
App.js
import Worker from "./file.worker.js";
const worker = new Worker();
worker.postMessage({ a: 1 });
worker.onmessage = function (event) {};
worker.addEventListener("message", function (event) {});
And run webpack
via your preferred method.
Name | Type | Default | Description |
---|---|---|---|
Name Type Default Description
|
{String\|Object} |
Worker |
Allows to set web worker constructor name and options |
Name Type Default Description
|
{String\|Function} |
based on
output.publicPath |
specifies the public URL address of the output files when referenced in a browser |
Name Type Default Description
|
{String\|Function} |
based on
output.filename |
The filename of entry chunks for web workers |
Name Type Default Description
|
{String} |
based on
output.chunkFilename |
The filename of non-entry chunks for web workers |
Name Type Default Description
|
'no-fallback'\|'fallback' |
undefined |
Allow to inline the worker as a
BLOB |
Name Type Default Description
|
{Boolean} |
true |
Use ES modules syntax |
worker
Type: String|Object
Default: Worker
Set the worker type.
String
Allows to set web worker constructor name.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.worker\.(c|m)?js$/i,
loader: "worker-loader",
options: {
worker: "SharedWorker",
},
},
],
},
};
Object
Allow to set web worker constructor name and options.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.worker\.(c|m)?js$/i,
loader: "worker-loader",
options: {
worker: {
type: "SharedWorker",
options: {
type: "classic",
credentials: "omit",
name: "my-custom-worker-name",
},
},
},
},
],
},
};
publicPath
Type: String|Function
Default: based on output.publicPath
The publicPath
specifies the public URL address of the output files when referenced in a browser.
If not specified, the same public path used for other webpack assets is used.
String
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.worker\.(c|m)?js$/i,
loader: "worker-loader",
options: {
publicPath: "/scripts/workers/",
},
},
],
},
};
Function
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.worker\.(c|m)?js$/i,
loader: "worker-loader",
options: {
publicPath: (pathData, assetInfo) => {
return `/scripts/${pathData.hash}/workers/`;
},
},
},
],
},
};
filename
Type: String|Function
Default: based on output.filename
, adding worker
suffix, for example - output.filename: '[name].js'
value of this option will be [name].worker.js
The filename of entry chunks for web workers.
String
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.worker\.(c|m)?js$/i,
loader: "worker-loader",
options: {
filename: "[name].[contenthash].worker.js",
},
},
],
},
};
Function
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.worker\.(c|m)?js$/i,
loader: "worker-loader",
options: {
filename: (pathData) => {
if (
/\.worker\.(c|m)?js$/i.test(pathData.chunk.entryModule.resource)
) {
return "[name].custom.worker.js";
}
return "[name].js";
},
},
},
],
},
};
chunkFilename
Type: String
Default: based on output.chunkFilename
, adding worker
suffix, for example - output.chunkFilename: '[id].js'
value of this option will be [id].worker.js
The filename of non-entry chunks for web workers.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.worker\.(c|m)?js$/i,
loader: "worker-loader",
options: {
chunkFilename: "[id].[contenthash].worker.js",
},
},
],
},
};
inline
Type: 'fallback' | 'no-fallback'
Default: undefined
Allow to inline the worker as a BLOB
.
Inline mode with the fallback
value will create file for browsers without support web workers, to disable this behavior just use no-fallback
value.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.worker\.(c|m)?js$/i,
loader: "worker-loader",
options: {
inline: "fallback",
},
},
],
},
};
esModule
Type: Boolean
Default: true
By default, worker-loader
generates JS modules that use the ES modules syntax.
You can enable a CommonJS modules syntax using:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.worker\.(c|m)?js$/i,
loader: "worker-loader",
options: {
esModule: false,
},
},
],
},
};
The worker file can import dependencies just like any other file:
index.js
import Worker from "./my.worker.js";
var worker = new Worker();
var result;
worker.onmessage = function (event) {
if (!result) {
result = document.createElement("div");
result.setAttribute("id", "result");
document.body.append(result);
}
result.innerText = JSON.stringify(event.data);
};
const button = document.getElementById("button");
button.addEventListener("click", function () {
worker.postMessage({ postMessage: true });
});
my.worker.js
onmessage = function (event) {
var workerResult = event.data;
workerResult.onmessage = true;
postMessage(workerResult);
};
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.worker\.(c|m)?js$/i,
loader: "worker-loader",
options: {
esModule: false,
},
},
],
},
};
You can even use ES6+ features if you have the babel-loader
configured.
index.js
import Worker from "./my.worker.js";
const worker = new Worker();
let result;
worker.onmessage = (event) => {
if (!result) {
result = document.createElement("div");
result.setAttribute("id", "result");
document.body.append(result);
}
result.innerText = JSON.stringify(event.data);
};
const button = document.getElementById("button");
button.addEventListener("click", () => {
worker.postMessage({ postMessage: true });
});
my.worker.js
onmessage = function (event) {
const workerResult = event.data;
workerResult.onmessage = true;
postMessage(workerResult);
};
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.worker\.(c|m)?js$/i,
use: [
{
loader: "worker-loader",
},
{
loader: "babel-loader",
options: {
presets: ["@babel/preset-env"],
},
},
],
},
],
},
};
To integrate with TypeScript, you will need to define a custom module for the exports of your worker.
worker-loader!
typings/worker-loader.d.ts
declare module "worker-loader!*" {
// You need to change `Worker`, if you specified a different value for the `workerType` option
class WebpackWorker extends Worker {
constructor();
}
// Uncomment this if you set the `esModule` option to `false`
// export = WebpackWorker;
export default WebpackWorker;
}
my.worker.ts
const ctx: Worker = self as any;
// Post data to parent thread
ctx.postMessage({ foo: "foo" });
// Respond to message from parent thread
ctx.addEventListener("message", (event) => console.log(event));
index.ts
import Worker from "worker-loader!./Worker";
const worker = new Worker();
worker.postMessage({ a: 1 });
worker.onmessage = (event) => {};
worker.addEventListener("message", (event) => {});
worker-loader!
Alternatively, you can omit the worker-loader!
prefix passed to import
statement by using the following notation.
This is useful for executing the code using a non-WebPack runtime environment
(such as Jest with workerloader-jest-transformer
).
typings/worker-loader.d.ts
declare module "*.worker.ts" {
// You need to change `Worker`, if you specified a different value for the `workerType` option
class WebpackWorker extends Worker {
constructor();
}
// Uncomment this if you set the `esModule` option to `false`
// export = WebpackWorker;
export default WebpackWorker;
}
my.worker.ts
const ctx: Worker = self as any;
// Post data to parent thread
ctx.postMessage({ foo: "foo" });
// Respond to message from parent thread
ctx.addEventListener("message", (event) => console.log(event));
index.ts
import MyWorker from "./my.worker.ts";
const worker = new MyWorker();
worker.postMessage({ a: 1 });
worker.onmessage = (event) => {};
worker.addEventListener("message", (event) => {});
webpack.config.js
module.exports = {
module: {
rules: [
// Place this *before* the `ts-loader`.
{
test: /\.worker\.ts$/,
loader: "worker-loader",
},
{
test: /\.ts$/,
loader: "ts-loader",
},
],
},
resolve: {
extensions: [".ts", ".js"],
},
};
WebWorkers
are restricted by a same-origin policy, so if your webpack
assets are not being served from the same origin as your application, their download may be blocked by your browser.
This scenario can commonly occur if you are hosting your assets under a CDN domain.
Even downloads from the webpack-dev-server
could be blocked.
There are two workarounds:
Firstly, you can inline the worker as a blob instead of downloading it as an external script via the inline
parameter
App.js
import Worker from "./file.worker.js";
webpack.config.js
module.exports = {
module: {
rules: [
{
loader: "worker-loader",
options: { inline: "fallback" },
},
],
},
};
Secondly, you may override the base download URL for your worker script via the publicPath
option
App.js
// This will cause the worker to be downloaded from `/workers/file.worker.js`
import Worker from "./file.worker.js";
webpack.config.js
module.exports = {
module: {
rules: [
{
loader: "worker-loader",
options: { publicPath: "/workers/" },
},
],
},
};
Please take a moment to read our contributing guidelines if you haven't yet done so.
YAML frontmatter loader for webpack. Converts YAML in files to JSON.
This module requires a minimum of Node v6.9.0 and Webpack v4.0.0.
To begin, you'll need to install yaml-frontmatter-loader
:
$ npm install yaml-frontmatter-loader --save-dev
Then add the loader to your webpack
config. For example:
const json = require('yaml-frontmatter-loader!./file.md');
// => returns file.md as javascript object
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.md$/,
use: [ 'json-loader', 'yaml-frontmatter-loader' ]
}
]
}
}
And run webpack
via your preferred method.
webpack enables use of loaders to preprocess files. This allows you to bundle any static resource way beyond JavaScript. You can easily write your own loaders using Node.js.
Loaders are activated by using loadername!
prefixes in require()
statements, or are automatically applied via regex from your webpack configuration – see configuration.
raw-loader
Loads raw content of a file (utf-8)val-loader
Executes code as module and consider exports as JS codeurl-loader
Works like the file loader, but can return a data URL if the file is smaller than a limitfile-loader
Emits the file into the output folder and returns the (relative) URLref-loader
Create dependencies between any files manuallyjson-loader
Loads a JSON file (included by default)json5-loader
Loads and transpiles a JSON 5 filecson-loader
Loads and transpiles a CSON filescript-loader
Executes a JavaScript file once in global context (like in script tag), requires are not parsedbabel-loader
Loads ES2015+ code and transpiles to ES5 using Babelbuble-loader
Loads ES2015+ code and transpiles to ES5 using Bublétraceur-loader
Loads ES2015+ code and transpiles to ES5 using Traceurts-loader
or awesome-typescript-loader
Loads TypeScript 2.0+ like JavaScriptcoffee-loader
Loads CoffeeScript like JavaScriptfengari-loader
Loads Lua code using fengarielm-webpack-loader
Loads Elm like JavaScripthtml-loader
Exports HTML as string, require references to static resourcespug-loader
Loads Pug and Jade templates and returns a functionmarkdown-loader
Compiles Markdown to HTMLreact-markdown-loader
Compiles Markdown to a React Component using the markdown-parse parserposthtml-loader
Loads and transforms a HTML file using PostHTMLhandlebars-loader
Compiles Handlebars to HTMLmarkup-inline-loader
Inline SVG/MathML files to HTML. It’s useful when applying icon font or applying CSS animation to SVG.twig-loader
Compiles Twig templates and returns a functionstyle-loader
Add exports of a module as style to DOMcss-loader
Loads CSS file with resolved imports and returns CSS codeless-loader
Loads and compiles a LESS filesass-loader
Loads and compiles a SASS/SCSS filepostcss-loader
Loads and transforms a CSS/SSS file using PostCSSstylus-loader
Loads and compiles a Stylus filemocha-loader
Tests with mocha (Browser/NodeJS)eslint-loader
PreLoader for linting code using ESLintjshint-loader
PreLoader for linting code using JSHintjscs-loader
PreLoader for code style checking using JSCScoverjs-loader
PreLoader to determine the testing coverage using CoverJSvue-loader
Loads and compiles Vue Componentspolymer-loader
Process HTML & CSS with preprocessor of choice and require()
Web Components like first-class modulesangular2-template-loader
Loads and compiles Angular ComponentsFor more third-party loaders, see the list from awesome-webpack.