When your source code has gone through transformations, debugging becomes a problem. When debugging in a browser, how to tell where the original code is? Source maps solve this problem by providing a mapping between the original and the transformed source code. In addition to source compiling to JavaScript, this works for styling as well.
当你的源代码完成转换后,调试就成了一个问题。在浏览器中调试时,如何确认代码中的原始位置呢?Source maps 经过创建源码与转换后的代码之间的映射关系来解决这个问题。除了能够用在编译后的Javascript中,还能够用在样式中。javascript
One approach is to skip source maps during development and rely on browser support of language features. If you use ES2015 without any extensions and develop using a modern browser, this can work. The advantage of doing this is that you avoid all the problems related to source maps while gaining better performance.
在开发中不使用源码映射的方法是依赖于浏览器对语言特性的支持。若是你只使用ES015而不使用任何扩展而且在开发中使用现代浏览器,这是能够实现的。这样作的好处就是为了获取更好的性能时能够避免因为源码映射致使的性能降低问题。css
If you are using webpack 4 and the new mode
option, the tool will generate source maps automatically for you in development
mode. Production usage requires attention, though.
若是你在使用Webpack4而且使用 mode
选项,在development
模式下,Webpack会自动生成源码映射关系。可是须要注意生产环境的使用。html
T> If you want to understand the ideas behind source maps in greater detail, read Ryan Seddon's introduction to the topic.
若是想深刻了解source map的机制,能够读Ryan Seddon的介绍.html5
T> To see how webpack handles source maps, see source-map-visualization by the author of the tool.
T> 想了解webpack如何处理源码映射, 查看工具做者写的source-map-visualization .java
Webpack can generate both inline or separate source map files. The inline ones are valuable during development due to better performance while the separate ones are handy for production use as it keeps the bundle size small. In this case, loading source maps is optional.
Webpack便可以生成内联源码映射也能够生成分离源码映射。内联源码映射在开发时很是有用,而为了追求生产环境中更好的性能,分离源码映射经过保持Bundle的文件更小而更加方便。这种状况下,加载源码映射是选择性的。webpack
It's possible you don't want to generate a source map for your production bundle as this makes it effortless to inspect your application. By disabling source maps, you are performing a sort of obfuscation. Whether or not you want to enable source maps for production, they are handy for staging. Skipping source maps speeds up your build as generating source maps at the best quality can be a complicated operation.
你必定不想在生产环境中生成源码映射,由于它能用来很是容易的分析你的程序。经过禁用源码映射,你要执行一系列混淆。不管你想不想启用源码映射,可是它们对于演示来讲很是方便。跳过源码映射能够加快你的构建速度,而生成源码映射能够提高质量,这可能成为一个复杂的操做。git
Hidden source maps give stack trace information only. You can connect them with a monitoring service to get traces as the application crashes allowing you to fix the problematic situations. While this isn't ideal, it's better to know about possible problems than not.
隐藏源码映射 只能提供堆栈跟踪信息。在程序崩溃的时候,可让你把他们链接到监视服务来获取跟踪信息来解决有问题的状况。虽然这样并不理想,可是知道可能的问题总比不知道要好。github
T> It's a good idea to study the documentation of the loaders you are using to see loader specific tips. For example, with TypeScript, you have to set a particular flag to make it work as you expect.
学习你在使用的加载器的具体提示是个好主意。例如,在Typescript中,你得设置一个标志才能让它按照预想的方式工做。web
Webpack provides two ways to enable source maps. There's a devtool
shortcut field. You can also find two plugins that give more options to tweak. The plugins are going to be discussed briefly at the end of this chapter. Beyond webpack, you also have to enable support for source maps at the browsers you are using for development.
Webpack有两种方式来启用源码映射。有一个字段devtool
。你也能找到两个插件,他们能提供更多的选项作进一步配置。这些插件将在本文最后作个简单的介绍。除了Webpack,咱们还得在开发使用的浏览器中启用源码映射支持。chrome
To get started, you can wrap the core idea within a configuration part. You can convert this to use the plugins later if you want:
在开始前,你能够把这个核心思想封装在一个配置部分中。若是愿意,你能够稍后将其转换成插件:
webpack.parts.js
exports.generateSourceMaps = ({ type }) => ({ devtool: type, });
Webpack supports a wide variety of source map types. These vary based on quality and build speed. For now, you enable source-map
for production and let webpack use the default for development. Set it up as follows:
Webpack支持不少种源码映射类型。他们的不一样在于质量和构建速度。如今,为生产环境启用source-map
而且让webpack对开发环境使用默认配置。按以下方式配置:
webpack.config.js
const productionConfig = merge([ leanpub-start-insert parts.generateSourceMaps({ type: "source-map" }), leanpub-end-insert ... ]);
source-map
is the slowest and highest quality option of them all, but that's fine for a production build.source-map
是最慢可是质量却最高的,这对生产环境构建很适合。
{pagebreak}
If you build the project now (npm run build
), you should see source maps in the output:
若是你如今构建项目(npm run build
),就能在输出中看到源码映射:
Hash: b59445cb2b9ae4cea11b Version: webpack 4.1.1 Time: 1347ms Built at: 3/16/2018 4:58:14 PM Asset Size Chunks Chunk Names main.js 838 bytes 0 [emitted] main main.css 3.49 KiB 0 [emitted] main main.js.map 3.75 KiB 0 [emitted] main main.css.map 85 bytes 0 [emitted] main index.html 220 bytes [emitted] Entrypoint main = main.js main.css main.js.map main.css.map ...
Take a good look at those .map files. That's where the mapping between the generated and the source happens. During development, it writes the mapping information in the bundle.
仔细查看这些 .map 文件。这就是保存源码和编译后的代码的映射关系的地方。在开发的时候,它把映射信息直接写到Bundle中。
To use source maps within a browser, you have to enable source maps explicitly as per browser-specific instructions:
要想在浏览器中使用源码映射,你得根据不一样浏览器的具体介绍准确启用源码映射。
W> If you want to use breakpoints (i.e., a debugger;
statement or ones set through the browser), the eval
-based options won't work in Chrome!
若是你想用断点(例如,一个debugger
语句或者经过浏览器设置),在chrome中基于eval
的选项不起做用。
Source map types supported by webpack can be split into two categories:
Webpack支持的源码映射能够分为两类:
Thanks to their speed, inline source maps are ideal for development. Given they make the bundles big, separate source maps are the preferred solution for production. Separate source maps work during development as well if the performance overhead is acceptable.
内联源码映射因为速度快很是适合开发使用。因为他们使Bundle变大,分离的源码映射更受到生产环境的青睐。若是性能开销能够接受,分离源码映射也能够用在开发中。
Webpack provides multiple inline source map variants. Often eval
is the starting point and webpack issue #2145 recommends cheap-module-eval-source-map
as it's a good compromise between speed and quality while working reliably in Chrome and Firefox browsers.
Webpack提供多种内联源码映射变体。eval
一般做为开始点,在webpack issue #2145中推荐使用cheap-module-eval-source-map
因为其很好的平衡了速度和质量而且在Firefox和Chrome中运行稳定。
To get a better idea of the available options, they are listed below while providing a small example for each. The source code contains only a single console.log('Hello world')
and webpack.NamedModulesPlugin
is used to keep the output easier to understand. In practice, you would see a lot more code to handle the mapping.
为了更好的离解可用的选项,下面列举并使用短小的例子进行说明。源码中只包含一句console.log('Hello world')
而且 webpack.NamedModulesPlugin
保证输出更易于理解 。在实际中,你将会看到更多的代码来处理映射关系。
devtool: "eval"
eval
generates code in which each module is wrapped within an eval
function:eval
生成代码,每一个模块都封装在一个eval
函数中:
webpackJsonp([1, 2], { "./src/index.js": function(module, exports) { eval("console.log('Hello world');\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/index.js\n// module id = ./src/index.js\n// module chunks = 1\n\n//# sourceURL=webpack:///./src/index.js?") } }, ["./src/index.js"]);
devtool: "cheap-eval-source-map"
cheap-eval-source-map
goes a step further and it includes base64 encoded version of the code as a data url. The result contains only line data while losing column mappings.cheap-eval-source-map
更进一步,它包含base64编码版本的代码做为数据的URL。结果中只包含行数据而没有列的映射数据。
webpackJsonp([1, 2], { "./src/index.js": function(module, exports) { eval("console.log('Hello world');//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiLi9hcHAvaW5kZXguanMuanMiLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9hcHAvaW5kZXguanM/MGUwNCJdLCJzb3VyY2VzQ29udGVudCI6WyJjb25zb2xlLmxvZygnSGVsbG8gd29ybGQnKTtcblxuXG4vLy8vLy8vLy8vLy8vLy8vLy9cbi8vIFdFQlBBQ0sgRk9PVEVSXG4vLyAuL2FwcC9pbmRleC5qc1xuLy8gbW9kdWxlIGlkID0gLi9hcHAvaW5kZXguanNcbi8vIG1vZHVsZSBjaHVua3MgPSAxIl0sIm1hcHBpbmdzIjoiQUFBQSIsInNvdXJjZVJvb3QiOiIifQ==") } }, ["./src/index.js"]);
{pagebreak}
If you decode that base64 string, you get output containing the mapping:
若是解码base64的字符串,就能获得包含映射关系的输出:
{ "file": "./src/index.js", "mappings": "AAAA", "sourceRoot": "", "sources": [ "webpack:///./src/index.js?0e04" ], "sourcesContent": [ "console.log('Hello world');\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./src/index.js\n// module id = ./src/index.js\n// module chunks = 1" ], "version": 3 }
devtool: "cheap-module-eval-source-map"
cheap-module-eval-source-map
is the same idea, except with higher quality and lower performance:cheap-module-eval-source-map
也是相同的思路,只是质量更高,可是性能更低:
webpackJsonp([1, 2], { "./src/index.js": function(module, exports) { eval("console.log('Hello world');//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiLi9hcHAvaW5kZXguanMuanMiLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vYXBwL2luZGV4LmpzPzIwMTgiXSwic291cmNlc0NvbnRlbnQiOlsiY29uc29sZS5sb2coJ0hlbGxvIHdvcmxkJyk7XG5cblxuLy8gV0VCUEFDSyBGT09URVIgLy9cbi8vIGFwcC9pbmRleC5qcyJdLCJtYXBwaW5ncyI6IkFBQUEiLCJzb3VyY2VSb290IjoiIn0=") } }, ["./src/index.js"]);
{pagebreak}
Again, decoding the data reveals more:
再一次,解码数据揭示更多信息:
{ "file": "./src/index.js", "mappings": "AAAA", "sourceRoot": "", "sources": [ "webpack:///src/index.js?2018" ], "sourcesContent": [ "console.log('Hello world');\n\n\n// WEBPACK FOOTER //\n// src/index.js" ], "version": 3 }
In this particular case, the difference between the options is minimal.
在这个特定的状况中,选项之间的差别是很小的。
devtool: "eval-source-map"
eval-source-map
is the highest quality option of the inline options. It's also the slowest one as it emits the most data:eval-source-map
是内联选项中质量最高的选项。因为它产生最多的数据因此也是最慢的。
webpackJsonp([1, 2], { "./src/index.js": function(module, exports) { eval("console.log('Hello world');//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9hcHAvaW5kZXguanM/ZGFkYyJdLCJuYW1lcyI6WyJjb25zb2xlIiwibG9nIl0sIm1hcHBpbmdzIjoiQUFBQUEsUUFBUUMsR0FBUixDQUFZLGFBQVoiLCJmaWxlIjoiLi9hcHAvaW5kZXguanMuanMiLCJzb3VyY2VzQ29udGVudCI6WyJjb25zb2xlLmxvZygnSGVsbG8gd29ybGQnKTtcblxuXG4vLyBXRUJQQUNLIEZPT1RFUiAvL1xuLy8gLi9hcHAvaW5kZXguanMiXSwic291cmNlUm9vdCI6IiJ9") } }, ["./src/index.js"]);
{pagebreak}
This time around there's more mapping data available for the browser:
这回有更多的映射数据可供浏览器使用:
{ "file": "./src/index.js", "mappings": "AAAAA,QAAQC,GAAR,CAAY,aAAZ", "names": [ "console", "log" ], "sourceRoot": "", "sources": [ "webpack:///./src/index.js?dadc" ], "sourcesContent": [ "console.log('Hello world');\n\n\n// WEBPACK FOOTER //\n// ./src/index.js" ], "version": 3 }
Webpack can also generate production usage friendly source maps. These end up in separate files ending with .map
extension and are loaded by the browser only when required. This way your users get good performance while it's easier for you to debug the application.
Webpack还能生成适用于生产环境的源码映射。它们最终存入以.map
为扩展名的单独文件中,而且只在须要的状况下由浏览器加载。用户能够得到更好的性能,同时他也能够Debug程序。
source-map
is a reasonable default here. Even though it takes longer to generate the source maps this way, you get the best quality. If you don't care about production source maps, you can skip the setting there and get better performance in return.source-map
是这里理所固然的默认值。尽管按这种方式生成代码映射会耗费更长时间,可是你能得到更好的性能。若是你不介意生产环境的代码映射,能够跳过此步来获取更好的性能。
{pagebreak}
devtool: "cheap-source-map"
cheap-source-map
is similar to the cheap options above. The result is going to miss column mappings. Also, source maps from loaders, such as css-loader, are not going to be used.cheap-source-map
和上面介绍的简易选项同样。结果就是丢失列映射关系。此外,来自加载器的源码映射(如css-loader)将不能使用。
Examining the .map
file reveals the following output in this case:
在这个例子中,查看.map
文件能够获得如下输出:
{ "file": "main.9aff3b1eced1f089ef18.js", "mappings": "AAAA", "sourceRoot": "", "sources": [ "webpack:///main.9aff3b1eced1f089ef18.js" ], "sourcesContent": [ "webpackJsonp([1,2],{\"./src/index.js\":function(o,n){console.log(\"Hello world\")}},[\"./src/index.js\"]);\n\n\n// WEBPACK FOOTER //\n// main.9aff3b1eced1f089ef18.js" ], "version": 3 }
The source contains //# sourceMappingURL=main.9a...18.js.map
kind of comment at its end to map to this file.
源码结尾中包含 //# sourceMappingURL=main.9a...18.js.map
这样的注释来指向分离的映射文件。
{pagebreak}
devtool: "cheap-module-source-map"
cheap-module-source-map
is the same as previous except source maps from loaders are simplified to a single mapping per line. It yields the following output in this case:
除了加载器的源映射被简化为每行一个映射以外,cheap-module-source-map
与前面的映射是相同的。在这种状况下,它产生以下输出:
{ "file": "main.9aff3b1eced1f089ef18.js", "mappings": "AAAA", "sourceRoot": "", "sources": [ "webpack:///main.9aff3b1eced1f089ef18.js" ], "version": 3 }
W> cheap-module-source-map
is currently broken if minification is used and this is an excellent reason to avoid the option for now.
W> 若是使用了minification cheap-module-source-map
就会遭到破坏,这也成为不使用这个选项的绝佳理由.
devtool: "hidden-source-map"
hidden-source-map
is the same as source-map
except it doesn't write references to the source maps to the source files. If you don't want to expose source maps to development tools directly while you wish proper stack traces, this is handy.hidden-source-map
与source-map
同样,只不过它不会将源码映射的引用写入源文件中。若是您不想直接将源映射公开给开发工具,而但愿使用适当的堆栈跟踪,那么这是很是方便的。
devtool: "nosources-source-map"
nosources-source-map
creates a source map without sourcesContent
in it. You still get stack traces, though. The option is useful if you don't want to expose your source code to the client.nosources-source-map
建立的源码映射里不包含代码内容
。可是你仍是能获得堆栈跟踪信息。若是不想暴露源码给用户这个选项颇有用。
T> The official documentation contains more information about devtool
options.
T> The official documentation 包含更多关于 devtool
选项的信息.
{pagebreak}
devtool: "source-map"
source-map
provides the best quality with the complete result, but it's also the slowest option. The output reflects this:source-map
用完整的结果提供最好的质量,可是它也是最慢的选项。输出以下所示:
{ "file": "main.9aff3b1eced1f089ef18.js", "mappings": "AAAAA,cAAc,EAAE,IAEVC,iBACA,SAAUC,EAAQC,GCHxBC,QAAQC,IAAI,kBDST", "names": [ "webpackJsonp", "./src/index.js", "module", "exports", "console", "log" ], "sourceRoot": "", "sources": [ "webpack:///main.9aff3b1eced1f089ef18.js", "webpack:///./src/index.js" ], "sourcesContent": [ "webpackJsonp([1,2],{\n\n/***/ \"./src/index.js\":\n/***/ (function(module, exports) {\n\nconsole.log('Hello world');\n\n/***/ })\n\n},[\"./src/index.js\"]);\n\n\n// WEBPACK FOOTER //\n// main.9aff3b1eced1f089ef18.js", "console.log('Hello world');\n\n\n// WEBPACK FOOTER //\n// ./src/index.js" ], "version": 3 }
{pagebreak}
There are a couple of other options that affect source map generation:
还有其余一些选项影响源码映射的生成:
{ output: { // Modify the name of the generated source map file. // You can use [file], [id], and [hash] replacements here. // The default option is enough for most use cases. sourceMapFilename: '[file].map', // Default // This is the source map filename template. It's default // format depends on the devtool option used. You don't // need to modify this often. devtoolModuleFilenameTemplate: 'webpack:///[resource-path]?[loaders]' }, }
T> The official documentation digs into output
specifics.
T> 官方文档 深刻研究了output
的细节 .
W> If you are using UglifyJsPlugin
and still want source maps, you need to enable sourceMap: true
for the plugin. Otherwise, the result isn't what you expect because UglifyJS will perform a further transformation of the code, breaking the mapping. The same has to be done with other plugins and loaders performing changes. css-loader and related loaders are a good example.
W> 若是你在使用 UglifyJsPlugin
,而且想使用源码映射,你须要在插件中启用sourcemap:true
。不然,结果与你的预期会不一致,由于UglifyJS会执行更深刻的代码转换从而破坏了映射。在其余的插件和加载器中也须要作相应的修改。css-loader和相关的加载器就是很好的例子。
SourceMapDevToolPlugin
and EvalSourceMapDevToolPlugin
If you want more control over source map generation, it's possible to use the SourceMapDevToolPlugin or EvalSourceMapDevToolPlugin
instead. The latter is a more limited alternative, and as stated by its name, it's handy for generating eval
based source maps.
若是想对源码映射进行更多的控制,你可使用SourceMapDevToolPlugin 或者 EvalSourceMapDevToolPlugin
来代替. 后者是一种更有限的选择,正如其名称所述,它对于生成基于eval
的源码映射很是方便。
Both plugins can allow more granular control over which portions of the code you want to generate source maps for, while also having strict control over the result with SourceMapDevToolPlugin
. Using either plugin allows you to skip the devtool
option altogether.
这两个插件都容许更细粒度地控制要为哪部分代码生成源码映射, 同时还可使用“SourceMapDevToolPlugin”严格控制结果。使用任何一个插件均可以跳过“devtool”选项。
Given webpack matches only .js
and .css
files by default for source maps, you can use SourceMapDevToolPlugin
to overcome this issue. This can be achieved by passing a test
pattern like /\.(js|jsx|css)($|\?)/i
.
考虑到webpack生成源码匹配时默认只匹配 .js
和 .css
文件, 你可使用 SouceMapDevToolPlugin
来解决这个问题。能够经过传入一个 像/\.(js|jsx|css)($|\?)/i
`test这样的
test`模式来解决。
EvalSourceMapDevToolPlugin
accepts only module
and lineToLine
options as described above. Therefore it can be considered as an alias to devtool: "eval"
while allowing a notch more flexibility.
如上所述,EvalSourceMapDevToolPlugin
只接受module
和lineToLine
选项。所以能够把它当作是devtool: "eval"
的别称,只不过是配置更富弹性。
You can prefix a source map option with a pragma character that gets injected into the source map reference. Webpack uses #
by default that is supported by modern browsers, so you don't have to set it.
您能够在源码映射选项前面加上一个编译指示字符,该字符被注入到源码映射引用中。Webpack默认使用现代浏览器都支持的#
,因此不用特意去设置它。
To override this, you have to prefix your source map option with it (e.g., @source-map
). After the change, you should see //@
kind of reference to the source map over //#
in your JavaScript files assuming a separate source map type was used.
要替换它的话,你须要把它添加到源码映射选项的前面(例如:@source-map
).修改以后,若是是正在使用分离映射文件,你应该能在源码映射中看到//@
这样的引用而不是//#
。
Assuming you are using a package that uses inline source maps in its distribution, you can use source-map-loader to make webpack aware of them. Without setting it up against the package, you get minified debug output. Often you can skip this step as it's a special case.
假设你在使用一个包,它在使用内联源码映射,你可使用source-map-loader来让Webpack注意到他们。若是没有对这个包进行设置,你会得到较少的输出。因为这是一个特例,一般你能够路过此步。
If you want to enable source maps for styling files, you can achieve this by enabling the sourceMap
option. The same idea works with style loaders such as css-loader, sass-loader, and less-loader.
若是想在样式文件中使用源码映射,能够经过启用sourceMap
选项来实现。相同的想法对样式加载器如 css-loader, sass-loader和 less-loader也适用。
The css-loader is known to have issues when you are using relative paths in imports. To overcome this problem, you should set output.publicPath
to resolve the server url.
在imports中使用相对路径会致使 css-loader 的已知问题发生.要解决这个问题,你应该设置 output.publicPath
来处理服务器路径。
{pagebreak}
Source maps can be convenient during development. They provide better means to debug applications as you can still examine the original code over a generated one. They can be valuable even for production usage and allow you to debug issues while serving a client-friendly version of your application.
源码映射给开发带来了便利。他们提供了调试应用程序更好的方法,由于你仍然能够经过生成的代码检查原始代码。他们在生产环境中使用也是颇有意义而且让你能够在对用户友好的版本中调试问题。
To recap:(概述)
devtool: "source-map"
is the highest quality option making it valuable for production.devtool: "source-map"
是最高质量的选项,所以很是适合生产环境.cheap-module-eval-source-map
is a good starting point for development.cheap-module-eval-source-map
是开发的一个好起点。devtool: "hidden-source-map"
. You can capture the output and send it to a third party service for you to examine. This way you can capture errors and fix them.devtool: "hidden-source-map
。您能够捕获输出并将其发送到第三方服务以供检查。这样你 能捕获错误并修复他们。SourceMapDevToolPlugin
and EvalSourceMapDevToolPlugin
provide more control over the result than the devtool
shortcut.SourceMapDevToolPlugin
和 EvalSourceMapDevToolPlugin
比 devtool
对结果提供更多的控制。sourceMap
option per styling related loader you are using.sourceMap
选项。In the next chapter, you'll learn to split bundles and separate the current one into application and vendor bundles.在下一节中,你将学到分离bundle并将如今的Bundle分离到应用Bundle和供应商Bundle中。