起因
在学习 bootstrap 的过程中,在本地建立 template 文件时,因为引用的 js 和 css 文件都在本地,firefox 的 Web Developer Console 出现了如下的情况:
template 文件:
<!doctype html>
<html lang="en">
<head>
<title>Hello, world!</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="/bootstrap/4.0.0-beta.2/css/bootstrap-reboot.css" integrity="sha384-CG2f4SVxgq1wLtwrDBeiX2L5Wg+1PKca1S7conZoZeutVoX5rIaYeH6Lz/Zl5I+o" >
<link rel="stylesheet" href="/bootstrap/4.0.0-beta.2/css/bootstrap.css" integrity="sha384-D4uXGiV0A9/Qs6x3SL222p4SdrLx9Clo8ILGVQMoDDQ60FP2qozIG8TIvlq5itJW" >
</head>
<body>
<h1>Hello, world!</h1>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="/jquery-3.2.1.js" integrity="sha384-p7RDedFtQzvcp0/3247fDud39nqze/MUmahi6MOWjyr3WKWaMOyqhXuCT1sM9Q+l" ></script>
<script src="/popper-1.12.9.js" integrity="sha384-iHnbbhSOn6yYBGx9nxl9zSYhWF3+CK/hCiWZAZzQi/nHBHkC/ORFrBWSL9mPcWnH" ></script>
<script src="/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" ></script>
</body>
</html>
什么是 Source Maps,怎么这里就有一个 request 针对 popper.js.map 了 ?
什么是 Source Maps
因为性能的原因,站点引用的 css 和 js 文件通常都是合并和压缩的,但是这些文件是不适合做调试的,怎么办呢?source map 派上用场了:
A source map provides a way of mapping code within a compressed file back to it’s original position in a source file. This means that – with the help of a bit of software – you can easily debug your applications even after your assets have been optimized. The Chrome and Firefox developer tools both ship with built-in support for source maps.
具体请参考 An Introduction to Source Maps
那么怎么针对 popper.js.map 就有个 request 呢?答案在 poper.js 文件的最后一行:
//# sourceMappingURL=popper.js.map
因为本地并没有文件 popper.js.map,所以才出现之前图片中的 “Source map error” 。
生成 Source Maps 文件
留意的是 source maps 不止针对 js,还有 css 文件。怎样生成呢?UglifyJS2 (属于 Node.js package)是个不错的工具,可用来生成 js.map 文件,不知针对 css 文件如何?
如下,合并压缩了 js 文件同时生成了 js.map 文件:
uglifyjs js/file1.js js/file2.js \
-o foo.min.js -c -m \
--source-map "root='http://foo.com/src',url='foo.min.js.map'"