**configuration**
[[webpack官方网站 configuration](https://webpack.js.org/configuration/)]
Out of the box, webpack won't require you to use a configuration file. However, it will assume the entry point of your project is `src/index` and will output the result in `dist/main.js` minified and optimized for production.
Usually your projects will need to extend this functionality, for this you can create a `webpack.config.js` file in the root folder and webpack will automatically use it.
[TOC]
## Use different config file
If for some reason you want to use different config file depending on certain situations you can change this via command line by using the `--config` flag.
`webpack.config.js` is the default config file.
**package.json**
~~~
"scripts": {
"build": "webpack --config xx.config.js"
}
~~~
## Exporting
Besides exporting a single config object, there are a few more ways that cover other needs as well.
### Exporting a Function
The function is used to disambiguate in your `webpack.config.js` between [development](https://webpack.js.org/guides/development) and [production builds](https://webpack.js.org/guides/production).
The function will be invoked with two arguments:
* An environment as the first parameter. See the [environment options CLI documentation](https://webpack.js.org/api/cli#environment-options) for syntax examples.
* An options map (`argv`) as the second parameter. This describes the options passed to webpack, with keys such as [`output-filename`](https://webpack.js.org/api/cli/#output-options) and [`optimize-minimize`](https://webpack.js.org/api/cli/#optimize-options).
**webpack.config.js**
~~~diff
-module.exports = {
+module.exports = function(env, argv) {
+ return {
+ mode: env.production ? 'production' : 'development',
+ devtool: env.production ? 'source-maps' : 'eval',
plugins: [
new TerserPlugin({
terserOptions: {
+ compress: argv['optimize-minimize'] // only if -p or --optimize-minimize were passed
}
})
]
+ };
};
~~~
### Exporting a Promise
**webpack.config.js**
>[info] It is possible to export multiple promises by wrapping them into `Promise.all([/* Your promises */]).`
~~~js
module.exports = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
entry: './app.js',
/* ... */
});
}, 5000);
});
};
~~~
### Exporting multiple configurations
**webpack.config.js**
~~~js
module.exports = [{
output: {
filename: './dist-amd.js',
libraryTarget: 'amd'
},
name: 'amd',
entry: './app.js',
mode: 'production',
}, {
output: {
filename: './dist-commonjs.js',
libraryTarget: 'commonjs'
},
name: 'commonjs',
entry: './app.js',
mode: 'production',
}];
~~~
## Options
>[warning] Notice that throughout the configuration we use Node's built-in [path module](https://nodejs.org/api/path.html) and prefix it with the [`__dirname`](https://nodejs.org/docs/latest/api/globals.html#globals_dirname) global. This prevents file path issues between operating systems and allows relative paths to work as expected. See [this section](https://nodejs.org/api/path.html#path_windows_vs_posix) for more info on POSIX vs. Windows paths.
**webpack.config.js**
~~~
const path = require('path');
module.exports = {
mode: "production", // "production" | "development" | "none"
// Chosen mode tells webpack to use its built-in optimizations accordingly.
entry: "./app/entry", // string | object | array
// defaults to ./src
// Here the application starts executing and webpack starts bundling
output: {
// options related to how webpack emits results
path: path.resolve(__dirname, "dist"), // string
// the target directory for all output files
// must be an absolute path (use the Node.js path module)
filename: "bundle.js", // string
// the filename template for entry chunks
publicPath: "/assets/", // string
// the url to the output directory resolved relative to the HTML page
library: "MyLibrary", // string,
// the name of the exported library
libraryTarget: "umd", // universal module definition
// the type of the exported library
/* Advanced output configuration (click to show) */
/* Expert output configuration (on own risk) */
},
module: {
// configuration regarding modules
rules: [
// rules for modules (configure loaders, parser options, etc.)
{
test: /\.jsx?$/,
include: [
path.resolve(__dirname, "app")
],
exclude: [
path.resolve(__dirname, "app/demo-files")
],
// these are matching conditions, each accepting a regular expression or string
// test and include have the same behavior, both must be matched
// exclude must not be matched (takes preferrence over test and include)
// Best practices:
// - Use RegExp only in test and for filename matching
// - Use arrays of absolute paths in include and exclude
// - Try to avoid exclude and prefer include
issuer: { test, include, exclude },
// conditions for the issuer (the origin of the import)
enforce: "pre",
enforce: "post",
// flags to apply these rules, even if they are overridden (advanced option)
loader: "babel-loader",
// the loader which should be applied, it'll be resolved relative to the context
// -loader suffix is no longer optional in webpack2 for clarity reasons
// see webpack 1 upgrade guide
options: {
presets: ["es2015"]
},
// options for the loader
},
{
test: /\.html$/,
use: [
// apply multiple loaders and options
"htmllint-loader",
{
loader: "html-loader",
options: {
/ ... /
}
}
]
},
{ oneOf: [ / rules / ] },
// only use one of these nested rules
{ rules: [ / rules / ] },
// use all of these nested rules (combine with conditions to be useful)
{ resource: { and: [ / conditions / ] } },
// matches only if all conditions are matched
{ resource: { or: [ / conditions / ] } },
{ resource: [ / conditions / ] },
// matches if any condition is matched (default for arrays)
{ resource: { not: / condition / } }
// matches if the condition is not matched
],
/* Advanced module configuration (click to show) */
},
resolve: {
// options for resolving module requests
// (does not apply to resolving to loaders)
modules: [
"node_modules",
path.resolve(__dirname, "app")
],
// directories where to look for modules
extensions: [".js", ".json", ".jsx", ".css"],
// extensions that are used
alias: {
// a list of module name aliases
"module": "new-module",
// alias "module" -> "new-module" and "module/path/file" -> "new-module/path/file"
"only-module$": "new-module",
// alias "only-module" -> "new-module", but not "only-module/path/file" -> "new-module/path/file"
"module": path.resolve(__dirname, "app/third/module.js"),
// alias "module" -> "./app/third/module.js" and "module/file" results in error
// modules aliases are imported relative to the current context
},
/* Alternative alias syntax (click to show) */
/* Advanced resolve configuration (click to show) */
},
performance: {
hints: "warning", // enum
maxAssetSize: 200000, // int (in bytes),
maxEntrypointSize: 400000, // int (in bytes)
assetFilter: function(assetFilename) {
// Function predicate that provides asset filenames
return assetFilename.endsWith('.css') || assetFilename.endsWith('.js');
}
},
devtool: "source-map", // enum
// enhance debugging by adding meta info for the browser devtools
// source-map most detailed at the expense of build speed.
context: __dirname, // string (absolute path!)
// the home directory for webpack
// the entry and module.rules.loader option
// is resolved relative to this directory
target: "web", // enum
// the environment in which the bundle should run
// changes chunk loading behavior and available modules
externals: ["react", /^@angular/],
// Don't follow/bundle these modules, but request them at runtime from the environment
serve: { //object
port: 1337,
content: './dist',
// ...
},
// lets you provide options for webpack-serve
stats: "errors-only",
// lets you precisely control what bundle information gets displayed
devServer: {
proxy: { // proxy URLs to backend development server
'/api': 'http://localhost:3000'
},
contentBase: path.join(__dirname, 'public'), // boolean | string | array, static file location
compress: true, // enable gzip compression
historyApiFallback: true, // true for index.html upon 404, object for multiple paths
hot: true, // hot module replacement. Depends on HotModuleReplacementPlugin
https: false, // true for self-signed, object for cert authority
noInfo: true, // only errors & warns on hot reload
// ...
},
plugins: [
// ...
],
// list of additional plugins
/* Advanced configuration (click to show) */
~~~
### `context`
`string`
The base directory, an **absolute path**, for resolving entry points and loaders from configuration.
~~~js
module.exports = {
//...
context: path.resolve(__dirname, 'app')
};
~~~
By default the current directory is used, but it's recommended to pass a value in your configuration. This makes your configuration independent from CWD (current working directory).
### `entry`
`string | [string] | object { <key>: string | [string] } | (function: () => string | [string] | object { <key>: string | [string] })`
The point or points where to start the application bundling process. If an array is passed then all items will be processed.
A dynamically loaded module is **not** an entry point.
Simple rule: one entry point per HTML page.
**SPA**(Single Page Application): one entry point,
**MPA**(Multiple Page Application): multiple entry points.
~~~js
module.exports = {
//...
entry: {
home: './home.js',
about: './about.js',
contact: './contact.js'
}
};
~~~
### `mode`
~~~
module.exports = {
mode: "production", // "production" | "development" | "none"
}
};
~~~
If you want to change the behavior according to the **mode** variable inside the **webpack.config.js** , you have to export a function instead of an object:
~~~javascript
var config = {
entry: './app.js'
//...
};
module.exports = (env, argv) => {
if (argv.mode === 'development') {
config.devtool = 'source-map';
}
if (argv.mode === 'production') {
//...
}
return config;
};
~~~
### `output`
The top-level `output` key contains set of options instructing webpack on how and where it should output your bundles, assets and anything else you bundle or load with webpack.
* `output.filename`
* `output.library`
`string`or`object`(since webpack 3.1.0; for`libraryTarget: 'umd'`)
How the value of the `output.library` is used depends on the value of the `output.libraryTarget` option. Note that the default option for `output.libraryTarget` is `var`, so if the following configuration option is used:
**webpack.config.js**
~~~javascript
module.exports = {
//...
output: {
library: 'MyLibrary'
}
};
~~~
The variable `MyLibrary` will be bound with the return value of your entry file, if the resulting output is included as a script tag in an HTML page.
> Note that if an `array` is provided as an `entry` point, only the last module in the array will be exposed. If an `object` is provided, it can be exposed using an `array` syntax (see [this example](https://github.com/webpack/webpack/tree/master/examples/multi-part-library) for details).
* `output.libraryTarget`
`string: 'var'`
Configure how the library will be exposed. Any one of the following options can be used. Please note that this option works in conjunction with the value assigned to `output.library` .
* `output.chunkFilename`
`string`
This option determines the name of non-entry chunk files. See `output.filename` option for details on the possible values.
Note that these filenames need to be generated at runtime to send the requests for chunks. Because of this, placeholders like`[name]`and`[chunkhash]`need to add a mapping from chunk id to placeholder value to the output bundle with the webpack runtime. This increases the size and may invalidate the bundle when placeholder value for any chunk changes.
By default `[id].js` is used or a value inferred from `output.filename` (`[name]` is replaced with `[id]` or `[id].` is prepended).
* `output.path`
`string`
The output directory as an **absolute** path.
**webpack.config.js**
~~~javascript
module.exports = {
//...
output: {
path: path.resolve(__dirname, 'dist/assets')
}
};
~~~
Note that `[hash]` in this parameter will be replaced with an hash of the compilation.
* `output.pathInfo`
`boolean`
Tells webpack to include comments in bundles with information about the contained modules. This option defaults to `true` in `development` and `false` in`production` mode.
> While the data this comments can provide is very useful during development when reading the generated code, it **should not** be used in production.
* `output.publicPath`
`string: ''` `function`
This is an important option when using on-demand-loading or loading external resources like images, files, etc. If an incorrect value is specified you'll receive 404 errors while loading these resources.
This option specifies the**public URL**of the output directory when referenced in a browser. A relative URL is resolved relative to the HTML page (or`<base>`tag). Server-relative URLs, protocol-relative URLs or absolute URLs are also possible and sometimes required, i. e. when hosting assets on a CDN.
The value of the option is prefixed to every URL created by the runtime or loaders. Because of this**the value of this option ends with`/`**in most cases.
Simple rule: The URL of your[`output.path`](https://webpack.js.org/configuration/output/#outputpath)from the view of the HTML page.
**webpack.config.js**
~~~javascript
module.exports = {
//...
output: {
path: path.resolve(__dirname, 'public/assets'),
publicPath: 'https://cdn.example.com/assets/'
}
};
~~~
For this configuration:
**webpack.config.js**
~~~javascript
module.exports = {
//...
output: {
publicPath: '/assets/',
chunkFilename: '[id].chunk.js'
}
};
~~~
A request to a chunk will look like`/assets/4.chunk.js`.
A loader outputting HTML might emit something like this:
~~~html
<link href="/assets/spinner.gif" />
~~~
or when loading an image in CSS:
~~~css
background-image: url(/assets/spinner.gif);
~~~
The webpack-dev-server also takes a hint from`publicPath`, using it to determine where to serve the output files from.
Note that`[hash]`in this parameter will be replaced with an hash of the compilation. See the[Caching guide](https://webpack.js.org/guides/caching)for details.
Examples:
~~~javascript
module.exports = {
//...
output: {
// One of the below
publicPath: 'https://cdn.example.com/assets/', // CDN (always HTTPS)
publicPath: '//cdn.example.com/assets/', // CDN (same protocol)
publicPath: '/assets/', // server-relative
publicPath: 'assets/', // relative to HTML page
publicPath: '../assets/', // relative to HTML page
publicPath: '', // relative to HTML page (same directory)
}
};
~~~
In cases where the`publicPath`of output files can't be known at compile time, it can be left blank and set dynamically at runtime in the entry file using the [free variable](https://stackoverflow.com/questions/12934929/what-are-free-variables) `__webpack_public_path__`.
~~~javascript
__webpack_public_path__ = myRuntimePublicPath;
// rest of your application entry
~~~
See [this discussion](https://github.com/webpack/webpack/issues/2776#issuecomment-233208623) for more information on `__webpack_public_path__`.
### `module`
These options determine how the [different types of modules](https://webpack.js.org/concepts/modules) within a project will be treated.
* `module.noParse`
`RegExp` `[RegExp]` `function(resource)` `string` `[string]`
Prevent webpack from parsing any files matching the given regular expression(s). Ignored files **should not** have calls to `import`, `require`, `define`or any other importing mechanism. This can boost build performance when ignoring large libraries.
**webpack.config.js**
~~~
module.exports = {
//...
module: {
noParse: /jquery|lodash/,
}
};
~~~
~~~
module.exports = {
//...
module: {
noParse: (content) => /jquery|lodash/.test(content)
}
};
~~~
* `module.rules`
`[Rule]`
An array of 'Rules' which are matched to requests when modules are created. These rules can modify how the module is created. They can apply loaders to the module, or modify the parser.
**webpack.config.js**
~~~
module.exports = {
//...
module: {
rules: [
//...
{
test: /\.json$/,
type: 'javascript/auto',
loader: 'custom-json-loader'
},
{
loader: 'file-loader',
options: {
outputPath: 'svgs'
}
},
(info) => ({
loader: 'svgo-loader',
options: {
plugins: [{
cleanupIDs: { prefix: basename(info.resource) }
}]
}
})
]
}
};
~~~
The`info`object parameter has the following fields:
* `compiler`: The current webpack compiler (can be undefined)
* `issuer`: The path to the module that is importing the module being loaded
* `realResource`: Always the path to the module being loaded
* `resource`: The path to the module being loaded, it is usually equal to `realResource` except when the resource name is overwritten via `!=!` in request string
### `resolve`
These options change how modules are resolved. webpack provides reasonable defaults, but it is possible to change the resolving in detail.
* `resolve`
`object`
Configure how modules are resolved. For example, when calling`import 'lodash'`in ES2015, the`resolve`options can change where webpack goes to look for`'lodash'`(see[`modules`](https://webpack.js.org/configuration/resolve/#resolvemodules)).
**webpack.config.js**
~~~js
module.exports = {
//...
resolve: {
// configuration options
}
};
~~~
* `resolve.alias`
`object`
Create aliases to`import`or`require`certain modules more easily. For example, to alias a bunch of commonly used`src/`folders:
**webpack.config.js**
~~~js
module.exports = {
//...
resolve: {
alias: {
Utilities: path.resolve(__dirname, 'src/utilities/'),
Templates: path.resolve(__dirname, 'src/templates/')
}
}
};
~~~
Now, instead of using relative paths when importing like so:
~~~js
import Utility from '../../utilities/utility';
~~~
you can use the alias:
~~~js
import Utility from 'Utilities/utility';
~~~
A trailing`$`can also be added to the given object's keys to signify an exact match:
**webpack.config.js**
~~~js
module.exports = {
//...
resolve: {
alias: {
xyz$: path.resolve(__dirname, 'path/to/file.js')
}
}
};
~~~
which would yield these results:
~~~js
import Test1 from 'xyz'; // Exact match, so path/to/file.js is resolved and imported
import Test2 from 'xyz/file.js'; // Not an exact match, normal resolution takes place
~~~
### `optimization`
Since version 4 webpack runs optimizations for you depending on the chosen `mode`, still all optimizations are available for manual configuration and overrides.
* `optimization.splitChunks`
`object`
By default webpack v4+ provides new common chunks strategies out of the box for dynamically imported modules. See available options for configuring this behavior in the [SplitChunksPlugin](https://webpack.js.org/plugins/split-chunks-plugin/) page.
* `optimization.namedModules`
`boolean: false`
Tells webpack to use readable module identifiers for better debugging. When `optimization.namedModules` is not set in webpack config, webpack will enable it by default for mode `development`and disable for mode `production`.
**webpack.config.js**
~~~js
module.exports = {
//...
optimization: {
namedModules: true
}
};
~~~
* `optimization.namedChunks`
`boolean: false`
Tells webpack to use readable chunk identifiers for better debugging. This option is enabled by default for[mode](https://webpack.js.org/configuration/mode/)`development`and disabled for[mode](https://webpack.js.org/configuration/mode/)`production`if no option is provided in webpack config.
**webpack.config.js**
~~~js
module.exports = {
//...
optimization: {
namedChunks: true
}
};
~~~
* `optimization.moduleIds`
`bool: false` `string: natural, named, hashed, size, total-size`
Tells webpack which algorithm to use when choosing module ids. Setting`optimization.moduleIds`to`false`tells webpack that none of built-in algorithms should be used, as custom one can be provided via plugin. By default`optimization.moduleIds`is set to`false`.
The following string values are supported:
| Option | Description |
| --- | --- |
| `natural` | Numeric ids in order of usage. |
| `named` | Readable ids for better debugging. |
| `hashed` | Short hashes as ids for better long term caching. |
| `size` | Numeric ids focused on minimal initial download size. |
| `total-size` | numeric ids focused on minimal total download size. |
**webpack.config.js**
~~~js
module.exports = {
//...
optimization: {
moduleIds: 'hashed'
}
};
~~~
* `optimization.chunkIds`
`bool: false` `string: natural, named, size, total-size`
Tells webpack which algorithm to use when choosing chunk ids. Setting`optimization.chunkIds`to`false`tells webpack that none of built-in algorithms should be used, as custom one can be provided via plugin. There are couple of defaults for`optimization.chunkIds`:
* if `optimization.occurrenceOrder` is enabled `optimization.chunkIds` is set to `'total-size'`
* Disregarding previous if, if `optimization.namedChunks` is enabled `optimization.chunkIds` is set to `'named'`
* if none of the above, `optimization.chunkIds` will be defaulted to `'natural'`
The following string values are supported:
| Option | Description |
| --- | --- |
| `'natural'`| Numeric ids in order of usage. |
| `'named'` | Readable ids for better debugging. |
| `'size'` | Numeric ids focused on minimal initial download size. |
| `'total-size'` | numeric ids focused on minimal total download size. |
**webpack.config.js**
~~~js
module.exports = {
//...
optimization: {
chunkIds: 'named'
}
};
~~~
* `optimization.nodeEnv`
`string` `bool: false`
Tells webpack to set `process.env.NODE_ENV` to a given string value. `optimization.nodeEnv` uses [DefinePlugin](https://webpack.js.org/plugins/define-plugin/)unless set to `false`. `optimization.nodeEnv` **defaults** to `mode` if set, else falls back to`"production"`.
Possible values:
* any string: the value to set `process.env.NODE_ENV` to.
* false: do not modify/set the value of `process.env.NODE_ENV`.
**webpack.config.js**
~~~js
module.exports = {
//...
optimization: {
nodeEnv: 'production'
}
};
~~~
### `plugins`
The `plugins` option is used to customize the webpack build process in a variety of ways. webpack comes with a variety built-in plugins available under `webpack.[plugin-name]`. See [Plugins page](https://webpack.js.org/plugins) for a list of plugins and documentation but note that there are a lot more out in the community.
* `plugins`
`[Plugin]`
An array of webpack plugins.
**webpack.config.js**
~~~js
var webpack = require('webpack');
// importing plugins that do not come by default in webpack
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var DashboardPlugin = require('webpack-dashboard/plugin');
// adding plugins to your configuration
module.exports = {
//...
plugins: [
new ExtractTextPlugin({
filename: 'build.min.css',
allChunks: true,
}),
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
// compile time plugins
new webpack.DefinePlugin({
'process.env.NODE_ENV': '"production"',
}),
// webpack-dev-server enhancement plugins
new DashboardPlugin(),
new webpack.HotModuleReplacementPlugin(),
]
};
~~~
### `devtool`
This option controls if and how source maps are generated.
Use the [`SourceMapDevToolPlugin`](https://webpack.js.org/plugins/source-map-dev-tool-plugin) for a more fine grained configuration. See the [`source-map-loader`](https://webpack.js.org/loaders/source-map-loader) to deal with existing source maps.
### `devServer`
[webpack-dev-server](https://github.com/webpack/webpack-dev-server) can be used to quickly develop an application. See the [development guide](https://webpack.js.org/guides/development/) to get started.
* `devServer`
`object`
This set of options is picked up by `webpack-dev-server` and can be used to change its behavior in various ways. Here's a simple example that gzips and serves everything from our `dist/` directory in the project root:
**webpack.config.js**
~~~javascript
var path = require('path');
module.exports = {
//...
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 9000
}
};
~~~
When the server is started, there will be a message prior to the list of resolved modules:
~~~bash
http://localhost:9000/
webpack output is served from /build/
Content not from webpack is served from /path/to/dist/
~~~
that will give some background on where the server is located and what it's serving.
### `target`
webpack can compile for multiple environments or*targets*. To understand what a`target`is in detail, read through[the targets concept page](https://webpack.js.org/concepts/targets/).
* `target`
`string | function (compiler)`
Instructs webpack to target a specific environment.
* `string`
The following string values are supported via [`WebpackOptionsApply`](https://github.com/webpack/webpack/blob/master/lib/WebpackOptionsApply.js):
| Option | Description |
| --- | --- |
| async-node` | Compile for usage in a Node.js-like environment (uses`fs`and`vm`to load chunks asynchronously) |
| `electron-main` | Compile for[Electron](https://electronjs.org/)for main process. |
| `electron-renderer` | Compile for[Electron](https://electronjs.org/)for renderer process, providing a target using`JsonpTemplatePlugin`,`FunctionModulePlugin`for browser environments and`NodeTargetPlugin`and`ExternalsPlugin`for CommonJS and Electron built-in modules. |
| `electron-preload` | Compile for[Electron](https://electronjs.org/)for renderer process, providing a target using`NodeTemplatePlugin`with`asyncChunkLoading`set to`true`,`FunctionModulePlugin`for browser environments and`NodeTargetPlugin`and`ExternalsPlugin`for CommonJS and Electron built-in modules. |
| `node` | Compile for usage in a Node.js-like environment (uses Node.js`require`to load chunks) |
| `node-webkit` | Compile for usage in WebKit and uses JSONP for chunk loading. Allows importing of built-in Node.js modules and[`nw.gui`](http://docs.nwjs.io/en/latest/)(experimental) |
| `web` | Compile for usage in a browser-like environment **(default)** |
| `webworker` | Compile as WebWorker |
* `function`
If a function is passed, then it will be called with the compiler as a parameter. Set it to a function if none of the predefined targets from the list above meet your needs.
For example, if you don't want any of the plugins they applied:
~~~js
const options = {
target: () => undefined
};
~~~
Or you can apply specific plugins you want:
~~~js
const webpack = require('webpack');
const options = {
target: (compiler) => {
compiler.apply(
new webpack.JsonpTemplatePlugin(options.output),
new webpack.LoaderTargetPlugin('web')
);
}
};
~~~
### `watch`
webpack can watch files and recompile whenever they change.
* `watch`
`boolean: false`
Turn on watch mode. This means that after the initial build, webpack will continue to watch for changes in any of the resolved files.
**webpack.config.js**
~~~javascript
module.exports = {
//...
watch: true
};
~~~
>[info] In `webpack-dev-server` and `webpack-dev-middleware` watch mode is enabled by default.
* `watchOptions`
`object`
A set of options used to customize watch mode:
**webpack.config.js**
~~~javascript
module.exports = {
//...
watchOptions: {
aggregateTimeout: 300,
poll: 1000
}
};
~~~
### `externals`
The `externals` configuration option provides a way of excluding dependencies from the output bundles. Instead, the created bundle relies on that dependency to be present in the consumer's environment. This feature is typically most useful to **library developers**, however there are a variety of applications for it.
>[info] **consumer** here is any end-user application that includes the library that you have bundled using webpack.
## Externals
The`externals`configuration option provides a way of excluding dependencies from the output bundles. Instead, the created bundle relies on that dependency to be present in the consumer's environment. This feature is typically most useful to **library developers**, however there are a variety of applications for it.
> **consumer** here is any end-user application that includes the library that you have bundled using webpack.
For example, to include `jQuery` from a CDN instead of bundling it:
**index.html**
~~~html
<script
src="https://code.jquery.com/jquery-3.1.0.js"
integrity="sha256-slogkvB1K3VOkzAI8QITxV3VzpOnkeNVsKvtkYLMjfk="
crossorigin="anonymous">
</script>
~~~
**webpack.config.js**
~~~javascript
module.exports = {
//...
externals: {
jquery: 'jQuery'
}
};
~~~
This leaves any dependent modules unchanged, i.e. the code shown below will still work:
~~~javascript
import $ from 'jquery';
$('.my-element').animate(/* ... */);
~~~
### `performance`
These options allows you to control how webpack notifies you of assets and entry points that exceed a specific file limit. This feature was inspired by the idea of [webpack Performance Budgets](https://github.com/webpack/webpack/issues/3216).
* `performance`
`object`
Configure how performance hints are shown. For example if you have an asset that is over 250kb, webpack will emit a warning notifying you of this.
### `node`
These options configure whether to polyfill or mock certain [Node.js globals](https://nodejs.org/docs/latest/api/globals.html) and modules. This allows code originally written for the Node.js environment to run in other environments like the browser.
This feature is provided by webpack's internal [`NodeStuffPlugin`](https://github.com/webpack/webpack/blob/master/lib/NodeStuffPlugin.js) plugin. If the target is "web" (default) or "webworker", the [`NodeSourcePlugin`](https://github.com/webpack/webpack/blob/master/lib/node/NodeSourcePlugin.js) plugin is also activated.
* `node`
`boolean: false | object`
This is an object where each property is the name of a Node global or module and each value may be one of the following...
* `true`: Provide a polyfill.
* `"mock"`: Provide a mock that implements the expected interface but has little or no functionality.
* `"empty"`: Provide an empty object.
* `false`: Provide nothing. Code that expects this object may crash with a`ReferenceError`. Code that attempts to import the module using`require('modulename')`may trigger a`Cannot find module "modulename"`error.
>[warning] Not every Node global supports all four options. The compiler will throw an error for property-value combinations that aren't supported (e.g.`process: 'empty'`). See the sections below for more details.
These are the defaults:
~~~js
module.exports = {
//...
node: {
console: false,
global: true,
process: true,
__filename: 'mock',
__dirname: 'mock',
Buffer: true,
setImmediate: true
// See "Other node core libraries" for additional options.
}
};
~~~
Since webpack 3.0.0, the `node` option may be set to `false` to completely turn off the `NodeStuffPlugin` and `NodeSourcePlugin` plugins.
### `stats`
The `stats` option lets you precisely control what bundle information gets displayed. This can be a nice middle ground if you don't want to use `quiet` or `noInfo` because you want some bundle information, but not all of it.
>[info] For webpack-dev-server, this property needs to be in the`devServer`object.
>[warning] This option does not have any effect when using the Node.js API.
- WebAPP
- Linux Command
- 入门
- 处理文件
- 查找文件单词
- 环境
- 联网
- Linux
- Linux目录配置标准:FHS
- Linux文件与目录管理
- Linux账号管理与ACL权限设置
- Linux系统资源查看
- 软件包管理
- Bash
- Daemon/Systemd
- ftp
- Apache
- MySQL
- Command
- Replication
- mysqld
- remote access
- remark
- 限制
- PHP
- String
- Array
- Function
- Class
- File
- JAVA
- Protocals
- http
- mqtt
- IDE
- phpDesigner
- eclipse
- vscode
- Notepad++
- WebAPI
- Javasript
- DOM
- BOM
- Event
- Class
- Module
- Ajax
- Fetch
- Promise
- async/await
- Statements and declarations
- Function
- Framwork
- jQurey
- Types
- Promise
- BootStrap
- v4
- ThinkPHP5
- install
- 定时任务
- CodeIgniter
- React.js
- node.js
- npm
- npm-commands
- npm-folder
- package.json
- Docker and private modules
- module
- webpack.js
- install
- configuration
- package.json
- entry
- modules
- plugins
- Code Splitting
- loaders
- libs
- API
- webpack-cli
- Vue.js
- install
- Compile
- VueAPI
- vuex
- vue-router
- vue-devtools
- vue-cli
- vue-loader
- VDOM
- vue-instance
- components
- template
- Single-File Components
- props
- data
- methods
- computed
- watch
- Event-handling
- Render Func
- remark
- 案例学习
- bootstrap-vue
- modal
- fontAwesome
- Hosting Font Awesome Yourself
- using with jquery
- using with Vue.js
- HTML
- CSS
- plugins
- Chart.js
- D3.js
- phpSpreadSheet
- Guzzle
- Cmder
- Git
- git命令
- git流程
- Postman
- Markdown
- Regular Expressions
- PowerDesigner
- 附录1-学习资源