简体   繁体   English

如何在Bower项目中包含javascript并使JSHint工作

[英]How to include javascript in a bower project and make JSHint work

I'm trying to use a bower library which I've installed according the the instructions with: 我正在尝试使用按照说明安装的Bower库:

bower install paper --save

This added a bower component, and I added this line to my index.html file: 这添加了一个Bower组件,并将这一行添加到了index.html文件中:

<!-- build:js scripts/vendor.js -->
<!-- bower:js -->
<script src="/bower_components/jquery/dist/jquery.js"></script>
<script src="/bower_components/paper/dist/paper-full.js"></script>  <-- I added
<!-- endbower -->
<!-- endbuild -->

According to the paper usage instructions, I can put all of my drawing code in a js file and include it, too. 根据纸张使用说明,我可以将所有绘图代码放入js文件中,并将其包括在内。 The docs weren't clear where in index.html to do this, and I don't really understand what those bower build comments are about, so I included it at the end of the head tag: 文档尚不清楚在index.html中的何处执行此操作,并且我不太了解这些Bower构建注释的含义,因此我将其包括在head标签的末尾:

    <script type="text/paperscript" src="scripts/script.js" canvas="canvas"></script>
</head>

Here's the problem: The code in my script.js file doesn't pass JSHint, even the first line that uses something from the paper library, like: 这是问题所在:我的script.js文件中的代码没有传递JSHint,即使第一行使用了纸库中的内容,也没有传递:

var circle = new Path();

generates a warning because "Path is not defined". 生成警告,因为“未定义路径”。

I understand that I can tell JSHint to ignore each of the paper symbols, but (a) there's a lot of them, and (b) I'd rather fix the problem rather than covering it up. 我知道我可以告诉JSHint忽略每个纸符号,但是(a)有很多纸符号,并且(b)我宁愿解决问题而不是掩盖它。

Am I going about adding this bower library the wrong way? 我要以错误的方式添加此Bower库吗? Is there a way I can add it so the symbols are known in my script? 有什么方法可以添加它,以便在脚本中知道符号?

When you import a library as a global variable, like you're doing with the paper library, you need to tell JSHint about it. 当您将库作为全局变量导入时,就像处理纸质库一样,您需要将其告知JSHint。 You can do that either by adding 您可以通过添加

{
    "predef": [ "paper" ]
}

to your .jshintrc config file (if you have one), or else by adding /* globals paper */ to the top of your files that use the paper library; .jshintrc配置文件中(如果有的话),或者在使用纸库的文件顶部添加/* globals paper */ then you should be able to do things like this without the linter complaining: 那么您应该能够做到以下事情而无需棉绒鞋抱怨:

var Path = paper.Path;
var circle = new Path();

The main way to avoid needing to define global variables like that, is to use some alternative setup for module loading other than global variables: there's a number of alternatives AMD (eg requireJS) CommonJS (eg Webpack), or ES6 modules. 避免像这样定义全局变量的主要方法是使用一些替代设置来加载模块而不是全局变量:有许多替代方案,例如AMD(例如requireJS),CommonJS(例如Webpack)或ES6模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM