// extract-source-from-source-map.js const fs = require("fs") const path = require("path") const util = require("util") const source = require("source-map") const writeFile = util.promisify(fs.writeFile) const mapFile = process.argv[2] if (!mapFile) { console.error('no input file given') process.exit(1) } // 读取“mapFile”路径下的所有.map文件 let dir = fs.readdirSync(mapFile) dir = dir.filter((name) => /\.map$/.test(name)).map(name => `${mapFile}${name}`) for (const valueMap of dir) { console.log("map file start: ", valueMap); const mapFileContent = fs.readFileSync(valueMap, 'utf-8') const outputDir = path.join(__dirname, 'output') fs.mkdirSync(outputDir, { recursive: true }) new source.SourceMapConsumer(mapFileContent).then(consumer => { Promise.all(consumer.sources.map(async (source) => { const content = consumer.sourceContentFor(source) const outputPath = path.join(outputDir, source) fs.mkdirSync(path.dirname(outputPath), { recursive: true }) return writeFile(outputPath, content) })) }).catch(console.error) } ,我来为大家讲解一下关于sourcemap的原理?跟着小编一起来看一看吧!

sourcemap的原理(通过source-map恢复源文件)

sourcemap的原理

通过source-map恢复源文件还原脚本

// extract-source-from-source-map.js const fs = require("fs") const path = require("path") const util = require("util") const source = require("source-map") const writeFile = util.promisify(fs.writeFile) const mapFile = process.argv[2] if (!mapFile) { console.error('no input file given') process.exit(1) } // 读取“mapFile”路径下的所有.map文件 let dir = fs.readdirSync(mapFile) dir = dir.filter((name) => /\.map$/.test(name)).map(name => `${mapFile}${name}`) for (const valueMap of dir) { console.log("map file start: ", valueMap); const mapFileContent = fs.readFileSync(valueMap, 'utf-8') const outputDir = path.join(__dirname, 'output') fs.mkdirSync(outputDir, { recursive: true }) new source.SourceMapConsumer(mapFileContent).then(consumer => { Promise.all(consumer.sources.map(async (source) => { const content = consumer.sourceContentFor(source) const outputPath = path.join(outputDir, source) fs.mkdirSync(path.dirname(outputPath), { recursive: true }) return writeFile(outputPath, content) })) }).catch(console.error) }

运行

node extract-source-from-source-map.js [source-map文件目录]

会在extract-source-from-source-map.js文件所在目录下的output目录输出源代码

,