If the production environment does not have source-map files, reported errors cannot be located. This section uses a simple error location script
1. Get error information of compressed code (number of lines, number of columns, error message, error file)
Here is the error message from the console
window.addEventListener('error'.function (e) {
console.debug('lineno: ', e.lineno, ' colno: ', e.colno)
console.debug('errorMessage:', e.message)
console.debug('errorFile:', e.filename)
}, true)
Copy the code
We write a bad piece of code (snippet of single.vue)
method: {
test (option) {
const data = option.test
const dataTest = option.data.test
return data + dataTest
}
},
created () {
The reason for setting asynchronous errors is that synchronous errors are caught by vUE
setTimeout(() => {
this.test({
testOption: 1
})
}, 300).
}
Copy the code
The following error message is displayed when the browser is running
Error message:
-
Error lines: 1
-
Number of error columns: 59236
-
Cannot read property ‘test’ of undefined
-
Error file: 0.0a77f.js
2. Locate the faulty Node script
Install dependencies on source-map
npm install source-map
Copy the code
The node script is as follows (map/index.js)
Var fs = require('fs'Var SourceMapConsumer = require()'source-map'SourceMapConsumer // Start the build process (not required if already built) varexec = require('child_process'). The exec var lineno = process. Argv [2] | | 0 / / the first parameter is the number of var columnno = process. The argv [3] | | 0 / / the second parameter is the number of columns var fileName = process.argv[4] ||' '// The third argument is an error file (the error file name is good) // Build online code with map // node build onlineMap is the build commandexec('node build onlineMap'.functionVar consumer = new SourceMapConsumer(fs.readfilesync ()'./dist/' + fileName + '.map'.'utf8')) / / output map error information to the console. The log (consumer) originalPositionFor ({line: + lineno, / / + is to be converted into digital column: + columnno}))})Copy the code
Running the Node script
Node map 1 59236 0.0a77f.jsCopy the code
The effect is as follows:
Combined with the console output, you can locate the error code
Let’s look again and turn on source-Map for the code to see if the error messages are consistent
3. Follow-up expansion ideas
Currently we implement a relatively simple script, so there are some problems:
- The current build needs to be consistent with the online content
- Complicated operation
The optimization idea is as follows:
Subsequent optimization slowly supplement ~
reference
Script error volume optimization – make the script error at a glance