首页 > 解决方案 > Rails 编译的 javascript 资产调试

问题描述

在捆绑了我的 javascript 资产的生产环境中,当我捕获到一个 javascript 错误时,我会得到它的行和列,例如:

d86c04c8f3.js:2:9588

现在,由于文件被缩小等,很难进行逆向工程并在源代码中找到有问题的行。给定 line/col 以找到原始线路,rails assets bundler 是否有办法进行逆向工程?这应该是可能的,因为资产构建器拥有它需要的所有信息。

我们需要一个简单的选项,运行 bundle exec rake assets:precompile RAILS_ENV=production 再次,但是这次指定 line+col,然后 rake 将输出源文件 + 对应于该资产 line+col 的 line。通过这种方式,我们可以轻松调试在客户端捕获的异常(并发送到服务器进行监控)。

编辑1

所有关于在客户端做某事的解决方案都是不可行的,因为我们无权访问客户端——我们谈论的是在生产模式、实时模式中发现的异常,以及正在发送到服务器进行监控的异常目的。

标签: javascriptruby-on-railsdebuggingassets

解决方案


For debugging minified scripts there're sourcemaps, once loaded in browser - you can see unminified code there.

Sprockets planned support for sourcemaps in 4.0, which is still not released yet (only a beta).

Webpack does support sourcemaps and rails 6 switched to webpacker by default, so converting scripts to packs seems logical, albeit being a massive task for large projects

Update: once you have source map for your build, you can use a tool like:

npx source-map-cli resolve d86c04c8f3.js.map 2 9588

This will tell you where in your code that position in minified file maps in the form of:

Maps to webpack:///app/javascript/components/CountrySelector.jsx:14:0

    fetch(`/control/autocomplete/countries`).then(r => r.json()).then(countries => this.setState({countries}))
    ^

推荐阅读