Restore Source Code Coverage
Frontend applications have various compilation forms. In many cases, pre-compiled AST is handed over to Babel for transformation, which makes it impossible to directly map coverage to source code. Therefore, we need to restore source code coverage.
Source Map
In frontend development, JavaScript code is often minified, obfuscated, or transformed using preprocessors (such as TypeScript, Babel) to improve performance and compatibility. These processes make the code deployed to production very different from the original source code, making debugging difficult. Source Map solves this problem by recording the mapping relationship between compiled code and original code, allowing developers to view and debug original code in browser developer tools. — web.dev
In most cases, you don’t need to manually obtain sourceMap files, because most build tools pass sourceMap files during the process of handing pre-compiled AST to Babel for transformation.
However, in some cases, you may need to configure sourceMap files.
Cases Where sourceMap Option Needs to Be Enabled
const path = require('path');
module.exports = {
entry: './build/main.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module:{
rules: [
{
test: /\.(js|jsx)$/,
use:['babel-loader'],
exclude:'/node_modules/'
}
]
}
};In this example, webpack’s entry file is ./build/main.js, which is the output of tsc compiling TypeScript files. We need to set sourceMap to true in tsconfig.json to ensure sourceMap data is passed.
{
"compilerOptions": {
"sourceMap": true
}
}Cases Where sourceMap Needs to Be Manually Set
When your sourceMap generation method falls into the following cases, you need to manually set sourceMap.
| Category | devtool | Description |
|---|---|---|
| Generate source map file, don’t show source code | hidden-source-map | Map file is not referenced at the end of the file |
| Generate source map file, don’t show source code | nosources-source-map | Map file is not referenced at the end of the file |
How to Manually Set sourceMap
In this case, you need to use Separate Hit and Map. Through Tools CLI, detect local sourceMap files during the build phase, and Canyon will match and upload them with initial coverage data.
This is also a disadvantage of JavaScript being too flexible. To collect accurate source code coverage data, we need to chain these sourceMap files together so that code instrumentation can correctly map to source code.