javascript - 使用多级源映射调试 Javascript

标签 javascript gruntjs google-chrome-devtools grunt-contrib-uglify grunt-contrib-concat

我有很多 javascript 文件,它们经过 grunt uglify 并单独缩小,此外,我对这些文件执行 grunt concat 以获得带有源映射的单个捆绑缩小文件。

例如

a.js, b.js, c.js -> Uglify -> a.min.js, b.min.js,c.min.js -> concat -> bundle.min.js

使用开发工具和源映射,从bundle.min.js,我只能追溯到a.min.js/b.min.js/c.min.js。 我的目标是使用源映射追溯到 a.js/b.js/c.js。

最佳答案

您的要求可以实现,但是您需要将任务顺序更改为以下顺序:

<小时/>

a.js、b.js、c.js --> concat --> bundle.js --> uglify --> bundle.min.js

<小时/>

注意:任务的顺序已更改为在丑化结果输出之前连接各个.js文件。

为什么需要改变任务顺序?

因为grunt-contrib-uglify提供sourceMapIn选项,同时 grunt-contrib-concat根本就没有。此外,在丑化文件之前连接文件是一种典型的做法。

sourceMapIn选项描述如下:

sourceMapIn

Type: String Function

Default: undefined

The location of an input source map from an earlier compilation, e.g. from CoffeeScript. If a function is provided, the uglify source is passed as the argument and the return value will be used as the sourceMap name. This only makes sense when there's one source file.

Gruntfile.js

您的 Gruntfile.js 可以配置如下:

module.exports = function(grunt) {

  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-concat');

  grunt.initConfig({
    concat: {
      options: {
        // ...
        sourceMap: true,
        sourceMapName: 'dist/js/bundle.map' // Specify path/name for sourceMap
      },
      my_target: {
        src: ['src/js/a.js', 'src/js/b.js', 'src/js/c.js'],
        dest: 'dist/js/bundle.js',
      },
    },
    uglify: {
      options: {
        // ...
        sourceMap: {
          includeSources: true
        },
        sourceMapIn: 'dist/js/bundle.map', // Specify the same path/name as
                                           // the `sourceMapName` value
                                           // in the `concat` task
      },
      my_target: {
        files: {
          'dist/js/bundle.min.js': ['dist/js/bundle.js']
        }
      }
    }
  });

  // Note we run the `concat` task before the `uglify` task.
  grunt.registerTask('default', ['concat:my_target', 'uglify:my_target']);
};

注释:

  1. concat.options.sourceMapNameuglify.options.sourceMapIn 指定的路径值必须相同,例如dist/js/bundle.map

  2. concat 任务必须在 uglify 任务之前运行。

  3. 需要根据您的项目要求定义这两个任务的 srcdest 路径。

关于javascript - 使用多级源映射调试 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49889109/

相关文章:

javascript - 文本框 - 如何不显示已填充的值

javascript - 用于将多个 Jquery 就绪函数组合成单个就绪函数的 Grunt 任务

javascript - AngularJS 与 Karma : $controller not defined error

gruntjs - 语法错误: Unexpected token ) in Gruntfile

google-chrome - 如何检查用户是否使用 chrome identity api 登录?

android - Facebook Stetho : Nothing shown, D/ChromeDevtoolsServer:方法未实现:未实现:null

java - 我如何为 Rhino 的 ScriptableObject 定义静态属性?

javascript - 将变量传递给带有单词边界的 RegExp

javascript - jQuery 自动完成 - 在不更改请求的情况下获取响应?

android - Chrome 远程调试 - "Pending Authentication"