从生产版本的javascript代码中删除断言

remove asserts from javascript code for production version

本文关键字:代码 删除 断言 javascript 版本      更新时间:2024-03-10

从生产版本的JavaScript代码中删除断言(console.assert)的最佳方法是什么?也许有一些软件可以配置为构建JavaScript并删除断言?

更新_____________________

我已经安装了GRENT和groundskeeper插件。这就是我的Gruntfile.js:

module.exports = function(grunt) {
    // Project configuration.
    grunt.initConfig({
    groundskeeper: {
        compile: {
            files: {
              'calculator/add.js': 'calculator/add.js'
            },
            options: {
                console: false
            }
        }
    }
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-groundskeeper');

问题是当我运行grunt groundskeeper时,我得到以下错误:

Running "groundskeeper:compile" (groundskeeper) task
Warning: Line 2: Invalid left-hand side in assignment Use --force to continue.

我认为问题出在这条线上:

'calculator/add.js': 'calculator/add.js'

因为如果我用以下内容替换它:

'path/to/result.js': 'path/to/source.js'

一切正常:

Running "groundskeeper:compile" (groundskeeper) task
>> File path/to/result.js created empty, because its counterpart was empty.
>> 1 files read, 0 cleaned.

我原来的台词怎么了?

将assert作为生产中的空函数

console.assert = function(){}

如果你能检查它是一个生产版本,那么把代码像

if (production) {
   console.assert = function(){}
}

对于旧的IE垫片

  if (typeof console == "undefined" || typeof console.assert == "undefined"){
       var console = { assert : function() {} }; 
    }

我正在使用grunt groundkeeper插件:
https://github.com/Couto/grunt-groundskeeper

如果你还没有使用Grunt,我真的建议你在JavaScript项目中使用它。解释如何使用Grunt本身超出了这个问题的范围。

以下示例配置将删除www/scripts.min.js文件中的所有日志记录语句设置为默认任务。

'use strict';
module.exports = function(grunt) {
    grunt.initConfig({
        groundskeeper: {
            dist: {
                files: {
                    'www/scripts.min.js': 'www/scripts.min.js'
                }
            }
        });
    grunt.loadNpmTasks('grunt-groundskeeper');
    grunt.registerTask('default', ['groundskeeper']);
};