webpack入门(三)webpack的api

时间:2023-03-08 17:21:09
webpack入门(三)webpack的api

终于到了webpack api这一篇,我都等不及了0.0;

webpack is fed a configuration object. Depending on your usage of webpack there are two ways to pass this configuration object:

webpack提供一个配置对象,取决于你咋用webpack,这有两种办法pass这个配置对象。

CLI

If you use the CLI it will read a file webpack.config.js (or the file passed by the --config option). This file should export the configuration object:

如果你用CLI,它只认webpack.config.js这个文件,(或者弄一个文件加一个--config的mark),这个文件就导出这个配置对象。

module.exports = {
// configuration
};

node.js API

If you use the node.js API you need to pass the configuration object as parameter: 用node,,需要将配置对象用参数传递进去,如下:

webpack({
// configuration
}, callback);

multiple configurations

In both cases you can also use an array of configurations, which are processed in parallel. They share filesystem cache and watchers so this is more efficent than calling webpack multiple times.      在这两种情况下,并行处理,你可以用个配置数组,他们共享文件系统缓存和watchers,比多次webpack调用更有效

CONFIGURATION OBJECT CONTENT

Hint: Keep in mind that you don’t need to write pure JSON into the configuration. Use any JavaScript you want. It’s just a node.js module…

提示:记住,不用在配置里写纯json文件,随便用js,它就是一个nodejs的模块

Very simple configuration object example:

{
context: __dirname + "/app",
entry: "./entry",
output: {
path: __dirname + "/dist",
filename: "bundle.js"
}

context

The base directory (absolute path!) for resolving the entry option. If output.pathinfo is set, the included pathinfo is shortened to this directory.

基础目录(绝对路径)用于解决entry这个选项,如果output.pathinfo设置了,就包含了缩短过的目录;(相当于公共目录,下面所有的目录都在这个公共目录下面)

Default: process.cwd()

entry

The entry point for the bundle.  打包文件的入口

If you pass a string: The string is resolved to a module which is loaded upon startup.      如果传入一个字符串,这个字符串就会被解析为启动时加载的模块。

If you pass an array: All modules are loaded upon startup. The last one is exported.  如果传入个数组,所有模块都是启动时加载,导出最后一个

entry: ["./entry1", "./entry2"]

If you pass an object: Multiple entry bundles are created. The key is the chunk name. The value can be a string or an array.

如果传入一个对象,就会创建多个输入包文件,对象键值就chunk的name,值可以是字符串或者是数组。

{
entry: {
page1: "./page1",
page2: ["./entry1", "./entry2"]
},
output: {
// Make sure to use [name] or [id] in output.filename
// when using multiple entry points
filename: "[name].bundle.js",
chunkFilename: "[id].bundle.js"
}
}

上面传了一个对象,page1和page2会生成两个打包文件,名字就是page1.bundle.js和page2.bundle.js,入口文件是3个,page1模块,entry1和entry2模块。

output

Options affecting the output of the compilation. output options tell Webpack how to write the compiled files to disk. Note, that while there can be multiple entry points, only one output configuration is specified.

If you use any hashing ([hash] or [chunkhash]) make sure to have a consistent ordering of modules. Use the OccurenceOrderPluginor recordsPath.

output是影响编译输出的选项。output选项告诉webpack怎么把编译文件写入磁盘。注意,虽然可以有很多输入口,但是只有一个输出配置

如果你用了很多hashing,确保有一个一致的模块顺序。用OccurenceOrderPlugin插件或者 recordsPath

output.filename

Specifies the name of each output file on disk. You must not specify an absolute path here! The output.path option determines the location on disk the files are written to, filename is used solely for naming the individual files.

指定每个输出文件的名字,你必须要指定一个绝对路径,output.path 选项决定了文件在磁盘上被写入的路径,filename仅被用于命名单个文件

single entry

{
entry: './src/app.js',
output: {
filename: 'bundle.js',
path: './built'
}
} // writes to disk: ./built/bundle.js

打包app.js文件,输出的bundle.js文件的路径为./built/bundle.js。

multiple entries    多个入口文件

If your configuration creates more than a single “chunk” (as with multiple entry points or when using plugins like CommonsChunkPlugin), you should use substitutions below to ensure that each file has a unique name.

如果你的配置文件创建了不只一个chunk的时候(就是多个入口文件或者用了 CommonsChunkPlugin插件的时候)(上面这个插件是提取文件公共的的部分,从而形成common的文件),你需要用个标记来确保每个chunk的名字不一样。下面这个些用于标记

[name] is replaced by the name of the chunk.   [name]在解析时会被替换为chunk的名字

[hash] is replaced by the hash of the compilation. [hash]会被替换成编译时的hash

[chunkhash] is replaced by the hash of the chunk. [chunkhash]会被替换为chunk的hash

{
entry: {
app: './src/app.js',
search: './src/search.js'
},
output: {
filename: '[name].js',
path: __dirname + '/built'
}
}
// writes to disk: ./built/app.js, ./built/search.js

webpack入门(三)webpack的api

输出为./built/app.js和 ./built/search.js

filename改为chunk会发生什么?

webpack入门(三)webpack的api

没错,就是第一行的hash做名字,绿色的那个文件为输出。

再换成chunkhash,webpack入门(三)webpack的api

生成两个文件,都是chunk的hash为文件名。

output.path

The output directory as absolute path (required).  output的目录作为绝对目录(required)

[hash] is replaced by the hash of the compilation. hash和上面一样,替换成编译时的hash值

output.publicPath

The publicPath specifies the public URL address of the output files when referenced in a browser. For loaders that embed <script>or <link> tags or reference assets like images, publicPath is used as the href or url() to the file when it’s different then their location on disk (as specified by path). This can be helpful when you want to host some or all output files on a different domain or on a CDN. The Webpack Dev Server also takes a hint from publicPath using it to determine where to serve the output files from. As with path you can use the [hash] substitution for a better caching profile.

publicPath这个选项当浏览器引用时会指定输出文件的公共url地址。对于嵌入<script>或者<link>标签或者一些像图片的资源的loaders来说,当磁盘上的路径(path指定的路径)和这里路径不同,publicPath被作为文件的href或者url。当你想在不同域上输出一下文件或者在CDN上publicPath很有用,Webpack Dev Server也需要用它来确定服务器的输出文件。你可以在用path的时候用[hash]替换为一个更好的缓存配置文件。

config.js

output: {
path: "/home/proj/public/assets",
publicPath: "/assets/"
}

index.html

<head>
<link href="/assets/spinner.gif"/>
</head>

编译的路径就在path写的绝对路径里面,引用就可以通过publicPath写的路径引用了,下面cdn也是一样

And a more complicated example of using a CDN and hashes for assets.

一个用CDN和hash资源更复杂的例子

config.js

output: {
path: "/home/proj/cdn/assets/[hash]",
publicPath: "http://cdn.example.com/assets/[hash]/"
}

Note: In cases when the eventual publicPath of output files isn’t known at compile time, it can be left blank and set dynamically at runtime in the entry point file. If you don’t know the publicPath while compiling you can omit it and set __webpack_public_path__ on your entry point.

如果最后的publicPath的输出文件不知道编译时间,在入口文件中,它可以被留白或者动态的设置运行时间。如果你不知道publicPath可以在编译时省略,可以在入口文件上设置__webpack_public_path__

 __webpack_public_path__ = myRuntimePublicPath

// rest of your application entry

output.chunkFilename

The filename of non-entry chunks as relative path inside the output.path directory.   output.path目录里的相当路径做为没有入口的chunks的名字

[id] is replaced by the id of the chunk.   [id]被替换为chunk的id

[name] is replaced by the name of the chunk (or with the id when the chunk has no name). [name]被替换为chunk的名字(没名字的时候用它id)

[hash] is replaced by the hash of the compilation.   [hash]被替换为编译时的hash

[chunkhash] is replaced by the hash of the chunk.   [chunkhash]被替换为每个chunk的hash

output.sourceMapFilename

The filename of the SourceMaps for the JavaScript files. They are inside the output.path directory.sourceMap文件的文件名,他们在output,path的目录里。

[file] is replaced by the filename of the JavaScript file.这些都和上面一样。这个选项是为source map功能准备的。

[id] is replaced by the id of the chunk.

[hash] is replaced by the hash of the compilation.

Default: "[file].map"

output.devtoolModuleFilenameTemplate

Filename template string of function for the sources array in a generated SourceMap.

[resource] is replaced by the path used by Webpack to resolve the file, including the query params to the rightmost loader (if any).

[resource]被替换为webpack解析文件的路径,包括查询参数的最右边的loader(如果有)

[resource-path] is the same as [resource] but without the loader query params.

[resource-path]和上面那个一样,但是不包含loader的查询参数

[loaders] is the list of loaders and params up to the name of the rightmost loader (only explict loaders).

[loaders]是loaders的目录和最右边loader的参数名(只显示loaders)

[all-loaders] is the list of loaders and params up to the name of the rightmost loader (including automatic loaders).

[all-loaders]同上(包括自动的loaders)

[id] is replaced by the id of the module.

[hash] is replaced by the hash of the module identifier.

[absolute-resource-path] is replaced with the absolute filename.

Default (devtool=[inline-]source-map): "webpack:///[resource-path]"
Default (devtool=eval): "webpack:///[resource-path]?[loaders]"
Default (devtool=eval-source-map): "webpack:///[resource-path]?[hash]"

Can also be defined as a function instead of a string template. The function will accept an info object parameter which exposes the following properties:

被定义为函数而不是字符串模板,这个函数接收一个暴露了下面一些属性的info对象参数。

    • identifier
    • shortIdentifier
    • resource
    • resourcePath
    • absoluteResourcePath
    • allLoaders
    • query
    • moduleId
    • hash

output.devtoolFallbackModuleFilenameTemplate

Similar to output.devtoolModuleFilenameTemplate, but used in the case of duplicate module identifiers.

和 output.devtoolModuleFilenameTemplate相同,但用在重复标识模块的时候。

Default: "webpack:///[resourcePath]?[hash]"

output.devtoolLineToLine

Enable line to line mapped mode for all/specified modules. Line to line mapped mode uses a simple SourceMap where each line of the generated source is mapped to the same line of the original source. It’s a performance optimization. Only use it if your performance need to be better and you are sure that input lines match which generated lines.

为所有模块启用行映射模式,行映射模式用了一个简单的SourceMap,用在了每一行生成的source映射到原始的source,这是一个性能优化,仅用在你的性能需要更佳,你确定输入行对应生成行的时候。

true enables it for all modules (not recommended)

true: 用在所有模块(不建议)

An object {test, include, exclude} similar to module.loaders enables it for specific files.

Default: disabled

output.hotUpdateChunkFilename

The filename of the Hot Update Chunks. They are inside the output.path directory.

热替换chunks的文件名。

[id] is replaced by the id of the chunk.

[hash] is replaced by the hash of the compilation. (The last hash stored in the records)

Default: "[id].[hash].hot-update.js"

output.hotUpdateMainFilename

The filename of the Hot Update Main File. It is inside the output.path directory.  热替换主文件的的名字。在output.path目录里。

[hash] is replaced by the hash of the compilation. (The last hash stored in the records)

Default: "[hash].hot-update.json"

output.jsonpFunction

The JSONP function used by webpack for asnyc loading of chunks.  jsonp函数被用于webpack异步加载chunks

A shorter function may reduce the filesize a bit. Use different identifier, when having multiple webpack instances on a single page.

一个精简的函数会减少很大的文件大小,当在单页中有多个webpack实例的时候用不同的标识。

Default: "webpackJsonp"

output.hotUpdateFunction

The JSONP function used by webpack for async loading of hot update chunks.

jsonp函数用于被用于webpack异步加载热替换的chunks

Default: "webpackHotUpdate"

output.pathinfo

Include comments with information about the modules.

包含一些模块的评论信息。

require(/* ./test */23)

Do not use this in production.

不要在生产环境下使用

Default: false

output.library

If set, export the bundle as library. output.library is the name.    如果设置了,导出的包就是库,名字为output.library

Use this, if you are writing a library and want to publish it as single file.      如果你写一个库,想发布为一个文件就用此选项。

output.libraryTarget

Which format to export the library:  导出库的格式

"var" - Export by setting a variable: var Library = xxx (default)        通过设置一个变量导出

"this" - Export by setting a property of thisthis["Library"] = xxx      通过设置this的属性导出

"commonjs" - Export by setting a property of exportsexports["Library"] = xxx   通过exports的属性导出

"commonjs2" - Export by setting module.exportsmodule.exports = xxx          通过设置module.exports导出

"amd" - Export to AMD (optionally named - set the name via the library option)   通过amd导出

"umd" - Export to AMD, CommonJS2 or as property in root

Default: "var"

If output.library is not set, but output.libraryTarget is set to a value other than var, every property of the exported object is copied (Except amdcommonjs2 and umd).

如果output.library没设置,但是output.libraryTarget设置了不是var的值,导出对象的每个属性都会被拷贝。(除了amd common.js2 和Umd)

output.umdNamedDefine

If output.libraryTarget is set to umd and output.library is set, setting this to true will name the AMD module.

如果output.libraryTarget设置为umd, output.library设置了,这个选项设为true将会给命名给amd模块

output.sourcePrefix

Prefixes every line of the source in the bundle with this string.

每行包文件的源文件的前缀都是字符串

Default: "\t"

output.crossOriginLoading

This option enables cross-origin loading of chunks.   这个选项用于跨域加载chunks

Possible values are:

false - Disable cross-origin loading.      设为false禁止跨域加载

"anonymous" - Cross-origin loading is enabled. When using anonymous no credentials will be send with the request.

允许跨域加载,用anonymous的时候,不会在请求发送证书。

"use-credentials" - Cross-origin loading is enabled and credentials will be send with the request.

允许跨域加载,会在请求中发送证书

For more information on cross-origin loading see MDN

Default: false