【发布时间】:2013-09-08 01:09:03
【问题描述】:
我使用 Yeoman 和backbone.js 编写了一个应用程序。在我指定的每个 js 文件的顶部 'use strict'; 并且当我运行我的 grunt 任务时,jshint 没有遇到任何错误。
我可以毫无问题地使用 grunt 构建我的应用程序,但是当我尝试运行 uglified js 时,我收到以下错误:
Uncaught SyntaxError: Strict mode code may not include a with statement
我搜索了代码库,唯一使用 with 语句的东西是下划线。
我是严格模式的新手,所以我不确定如何解决这个问题。在使用 underscorejs 函数的任何地方都不能使用严格模式吗?
谢谢。
编辑:
给定下面的代码示例(为简洁起见)。我怎样才能改变它来解决这个问题。
'use strict';
/*global, Backbone, JST*/
var MyView = Backbone.View.extend({
template: JST['app/scripts/templates/MyView.ejs'],
initialize: function()
{
this.render();
},
render : function()
{
this.$el.html(this.template(this.templateVariables()));
return this;
},
templateVariables: function()
{
return {var1 : 'Hello', var2 : 'World'};
}
});
在 MyView.ejs 中
<p><%= var1 %><%= var2 %>!</p> //<p>Hello World!</p>
编辑 2:
在下面使用@mu 太短的答案我发现解决对 _.template 的调用让我感到悲伤的最佳方法是将我的 grunt-JST 任务更改如下:
jst: {
compile: {
options:
{
templateSettings:
{
variable: 'data'
}
},
files: {
'.tmp/scripts/templates.js': ['<%= yeoman.app %>/scripts/templates/*.ejs']
}
}
},
然后将我的每个模板更改为使用<%= data.templateVariable %> 格式。
可能不适用于其他人,但我在使用带有 Grunt 和 Backbone 生成器的 Yeoman 时遇到了这个问题,所以我不能成为唯一的人。
【问题讨论】:
-
您是否在某处使用预编译的下划线模板? Underscore 中唯一的
with位于_.template生成的代码中,因此除非他们正在查看_.template生成的编译模板函数,否则任何人都不应该知道with的使用。 -
我明白了,你问我是否在 _.template() 任何地方使用?我是。我假设我需要在该文件中对严格模式更有选择性?
-
@mu 太短了——我做了更多的挖掘工作。我在整个应用程序中使用 JST 模板。预编译的 templates.js 在整个过程中使用 with 语句。所以我的问题就变成了我该如何解决这个问题?如果我在具有 JST 模板的视图文件中删除
use strict;指令,然后运行 grunt --force并忽略 jshint 错误,我仍然会得到与缩小的 js 相同的最终结果。想法?谢谢。
标签: javascript underscore.js yeoman underscore.js-templating