提升开发体验
大约 2 分钟
提升开发体验
SourceMap
为什么
开发时我们运行的代码是经过 webpack 编译后的,例如下面这个样子
/*
* ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development").
* This devtool is neither made for production nor for readable output files.
* It uses "eval()" calls to create a separate source file in the browser devtools.
* If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
* or disable the default devtool with "devtool: false".
* If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
*/
/******/ (() => { // webpackBootstrap
/******/ "use strict";
/******/ var __webpack_modules__ = ({
/***/ "./src/js/count.js":
/*!*************************!*\
!*** ./src/js/count.js ***!
\*************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"default\": () => (/* binding */ count)\n/* harmony export */ });\nfunction count(x, y) {\n return x - y;\n}\n\n//# sourceURL=webpack://webpack_code/./src/js/count.js?");
。。。。省略
所有的 css 和 js 合并成了一个文件,并且多了其他代码。此时如果代码运行出错那么提示代码错误位置我们是看不懂的。一旦将来开发代码文件很多,那么很难去发现错误出现在哪里。
所以我们需要更加准确的错误提示,来帮助我们更好的开发代码。
是什么
SourceMap (源代码映射)是一个用来生成源代码与构建后代码————映射的文件的方案。
它会生成一个 xx.map 文件,里面包含源代码和构建后代码每一行、每一列的映射关系。当构建后代码出错了,会通过 xx.map 文件,从构建后代码出错位置找到映射后源代码出错位置,从而让浏览器提示源代码文件出错位置,帮助我们更快的找到错误根源
怎么用
通过查看Webpack DevTool 文档可知,SourceMap 的值有很多种情况,
但实际开发时我们只需要关注两种情况即可:
开发模式:
cheap-module-source-map
- 优点:打包编译速度快,只包含行映射
- 缺点:没有列映射
module.exports={ mode: "development", devtool: "cheap-module-source-map" }
例如:sum.js 源文件
export default function sum(...args) { return args.reduce((p, c) => p + c, 0)(); // 后面加 () 使其报错 }
不开启 devtool 报错
开启 devtool 报错
生产模式:
source-map
- 优点:包含行/列映射
- 缺点:打包编译速度更慢
module.exports={ mode: "production", devtool: "source-map" }