SourceMap(ソースマップ)ってなんぞ

Advertisements
gulpJavaScript

gulpを使ってみて、gulp-sourcemapsというモジュールが便利そうだったので調べたことをメモ。そもそもSouceMapとは何か。

Advertisements

ソースマップとは

ブラウザで利用されているJavaScriptはコンパイルされているが、何かエラーが起こった際に、コンパイルされたままだとエラー箇所がよくわからず、不便。そのため、最適化やコンパイルされる前のJavaScriptを保持したソースファイルを作っておくと、後々便利、といったもの。

source map is a file that maps from the transformed source to the original source, enabling the browser to reconstruct the original source and present the reconstructed original in the debugger.
To enable the debugger to work with a source map, you must:
generate the source map
– generate the source map
– include a comment in the transformed file, that points to the source map. The comment’s syntax is like this:
//# sourceMappingURL=http://example.com/path/to/your/sourcemap.map

Use a source map

意訳:
ソースマップはオリジナルファイルから変換されたソースをマップしたファイルで、ブラウザがオリジナルのソースを再構築し、その再構築されたオリジナルをデバッガーに表示できるようにするものだ。
ソースマップでそのデバッガーを有効にするには、ソースマップを生成する必要がある。

  • まず、ソースマップを生成
  • 再構築されたファイル内に、ソースマップを指定するコメントを記述

コメントは以下の形式

//# sourceMappingURL=http://example.com/path/to/your/sourcemap.map

こうなることも想定

//# sourceMappingURL=main.js.map

動画でも解説あり。
https://youtu.be/Fqd15gHC4Pg

In the video above we load https://mdn.github.io/devtools-examples/sourcemaps-in-console/index.html. This page loads a source called “main.js” that was originally written in CoffeeScript and compiled to JavaScript. The compiled source contains a comment like this, that points to a source map:
//# sourceMappingURL=main.js.map
In the Debugger’s source list pane, the original CoffeeScript source now appears as “main.coffee”, and we can debug it just like any other source.

Use a source map

以下も意訳。元記事・動画はFirefoxを使っているが、意訳ではChromeを使用した場合の記載に書き換えている。

例えば、こちらのサンプルページ。
https://mdn.github.io/devtools-examples/sourcemaps-in-console/index.html

検証ツール-> Sources を開き、jsフォルダの中身を見てみよう。
このページでは、もともとCoffeeScriptで書かれ、コンパイルされたmain.jsというJavaScriptを読み込んでいる。このコンパイルされたソースコードには以下のコメントが挿入されており、これがソースマップを指しているのだ。

//# sourceMappingURL=main.js.map

デバッガーのSourcesパネルには、オリジナルのソースであるmain.coffeeが表示されており、まるで別のソースをいじるかのようにして、我々はこのソースをデバッグできるのである。

以上メモおしまい

タイトルとURLをコピーしました