创建的源映射指向系统路径,而不是相对路径

Source map created points to system paths instead of relative path

本文关键字:路径 相对 系统 映射 创建      更新时间:2023-09-26

我使用UglifyJS2将我的javascript源文件缩小为一个大的缩小文件。以下是我使用的相关代码:

var options = options || {};
options.outSourceMap = 'minfile.js.map';
try {
    // "scripts" is an array of absolute paths to the javascript files
    var minified = uglifyjs.minify(scripts, options);
    // minified.map contains the minfile
} catch (err) {
    // handle errs here
}

minfile本身包含到源文件的绝对路径:

{
    "version": 3,
    "file": "nodebb.min.js.map",
    "sources": [
        "/path/to/folder/jquery/js/jquery.js",
        "/path/to/folder/another/lib.js",
        ...
    ],
    ...
}

问题是,我传入的源文件是不可公开访问的,它们只被编译到minfile中,只有minfile是可访问的。因此,我的源映射似乎是毫无意义的,因为Chrome(在我的情况下)试图加载http://mydomain.com/path/to/folder/jquery/js/jquery.js而不是在我的本地fs上读取文件。

我做错了什么?

看起来UglifyJS2的回购是缺少一堆选项的节点API,但这个PR修复了一点:https://github.com/mishoo/UglifyJS2/pull/192

所以我现在在package.json中使用它:

"dependencies": {
    ...
    "uglify-js": "git+https://github.com/julianlam/UglifyJS2.git",
    ...
}

则可以将prefix传递到minify方法中,去掉路径中不需要的部分

另一个选择是使用"Hard Way"

在"source map generated "中使用

代替source_map.toString()
var json = source_map.get().toJSON();
json.sources = [ /* override sources */ ];
JSON.stringify(json);