我有一个Gruntfile.js
,如下所示闭包编译器配置,
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
'closure-compiler': {
jstracker: {
closurePath: '/usr/local/',
js: [
'src/js/banner.js',
'src/js/lib/json.js',
'src/js/lib/jstz.js',
'src/js/init.js',
'src/js/helpers.js',
'src/js/lib/sha1.js',
'src/js/lib/murmur.js',
'src/js/lib/base64.js',
'src/js/tracker.js',
'src/js/prayagupd.js',
'src/js/constructor.js'
],
jsOutputFile: 'dist/<%= pkg.name %>.min.js',
options: {
compilation_level: 'ADVANCED_OPTIIZATIONS',
warning_level:"DEFAULT",
language_in: 'ECMASCRIPT5_STRICT'
}
}
},
qunit: {
files: ['tests/**/*.html']
},
jshint: {
files: ['Gruntfile.js', 'src/**/*.js', 'tests/*.js'],
options: {
// options here to override JSHint defaults
globals: {
jQuery: true,
console: true,
module: true,
document: true
}
}
},
watch: {
files: ['<%= jshint.files %>'],
tasks: ['jshint', 'qunit']
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-qunit');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-closure-compiler');
grunt.registerTask('test', ['jshint', 'closure-compiler', 'qunit']);
grunt.registerTask('default', ['jshint', 'closure-compiler', 'qunit']);
};
当我执行grunt
生成缩小的js时,我在target
文件夹中看到缩小版本,
$ ls -lh dist/
total 44K
-rw-rw-r-- 1 prayagupd prayagupd 27K Jul 6 16:34 prayagupd.min.js
-rw-rw-r-- 1 prayagupd prayagupd 514 Jul 6 16:34 prayagupd.min.js.report.txt
但是随后的4条警告都指向使用this
,后来在浏览器中使用时会弹出错误(Uncaught ReferenceError: JSON2 is not defined
)。
src/js/lib/json.js:26: WARNING - dangerous use of the global this object
if (!this.JSON2) {
^
src/js/lib/json.js:27: WARNING - dangerous use of the global this object
this.JSON2 = {};
^
src/js/leakers.js:1995: WARNING - dangerous use of the global this object
this.setContextProperty("leaksId", leaksId);
^
src/js/leakers.js:2002: WARNING - dangerous use of the global this object
this.setContextProperty("userId", userId);
^
0 error(s), 4 warning(s)
SIMPLE_OPTIMIZATIONS
级别可以正常工作。
//src/js/lib/json.js:26
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
if (!this.JSON2) {
this.JSON2 = {};
}
和
//src/js/leakers.js
/**
* Set context properties, properties which are used with every event
*/
setContextProperty: function(name, value) {
context[name] = value;
},
/**
* Set leaks ID
*/
setLeakesId: function(leakesId) {
this.setContextProperty("leakesId", leakesId);
},
/**
* Set user ID
*/
setUserId: function(userId){
this.setContextProperty("userId", userId);
}
1)要求关闭忽略this
,这在ADVANCED_OPTIMIZATIONS
或
2)找到替换this
并开始工作的方法。
答案 0 :(得分:4)
编译器基本上警告您使用“this”的方式不确定(您可能不小心使用全局)并且可能与高级编译不兼容。您想要验证“this”值是否正确,并使用@this注释向编译器指示。
此警告记录在此处: https://developers.google.com/closure/compiler/docs/error-ref