javascript - 如何在我的 JavaScript 代码的 PhpStorm 中包含 "require"?

标签 javascript requirejs phpstorm js-test-driver canvg

我正在使用 canvg('canvas', svg); 行在我的代码中。这意味着我需要 canvg.js。

我在我的 html header 中包含了 canvg.js。但是它给了我一个错误,“require is undefined”。

对于那些不知道 canvg.js 前两行的人是:

var RGBColor = require('rgbcolor'),
    StackBlur = require('stackblur-canvas');

这首先作为错误出现在我的控制台中。这并不是真正的问题,因为代码仍然有效。

虽然错误导致测试无法运行,但现在我要开始测试了。这是一个问题。

error loading file: /test/tests/Dependencies/canvg.js:4: Uncaught ReferenceError: require is not defined

我去了https://requirejs.org/docs/release/2.3.6/comments/require.js并将代码复制并粘贴到名为 require236.js 的文件中,并将其保存在我的项目中。

然后我转到我的 main.html 并添加了我的 <script src="require236.js"></script> 就在加载 canvg 之前。

我在控制台中遇到了这些错误:

 Uncaught Error: Mismatched anonymous define() module: function(){return f}
https://requirejs.org/docs/errors.html#mismatch
   at makeError (require236.js:168)
   at intakeDefines (require236.js:1254)
   at require236.js:1452
require236.js:143 Uncaught Error: Module name "rgbcolor" has not been loaded yet for context: _. Use require([])
https://requirejs.org/docs/errors.html#notloaded
  at makeError (require236.js:168)
  at Object.localRequire [as require] (require236.js:1436)
  at requirejs (require236.js:1797)
  at canvg.js:4

而且我的测试不会将该文件作为依赖项运行。

https://requirejs.org/docs/errors.html#mismatch

To avoid the error:

Be sure to load all scripts that call define() via the RequireJS API.

Do not manually code script tags in HTML to load scripts that have define() calls in them.

If you manually code an HTML script tag, be sure it only includes named modules, and that an anonymous module that will have the same name as one of the modules in that file is not loaded.

If the problem is the use of loader plugins or anonymous modules but the RequireJS optimizer is not used for file bundling, use the RequireJS optimizer.

If the problem is the var define lint approach, use /*global define */ (no space before "global") comment style instead.

但老实说,我不明白他们希望如何将它包括在内以及在哪里。如果您对它的理解足以解释它,请使用简单的英语单词(或仅显示代码示例)。

我正在从 PhpStorm 运行。我正在使用 jsTestDriver 进行测试。我一定是在以某种方式声明它是错误的,但我不知道 require.js 如何以及为什么会给我这样的问题。

最佳答案

简单的答案是,您包含的文件不应该在浏览器中运行,因为它使用只能在 node 运行的服务器端代码中使用的 CommonJS 语法.js.

您必须确保包含没有任何 require() 调用的库的浏览器版本,例如:

<script src="https://cdn.jsdelivr.net/npm/canvg/dist/browser/canvg.min.js"></script>

参见 https://github.com/canvg/canvg#usage-on-the-browser

关于javascript - 如何在我的 JavaScript 代码的 PhpStorm 中包含 "require"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57432316/

相关文章:

javascript - 如何对特定数字中的数字进行分类?

javascript - 如何检查 HTML 和 JavaScript 中的复选框是否为真?

javascript - Angular 6 typescript 与 KotlinJs 的集成

javascript - 如何在javascript文件中使用函数

PHPStorm、Xdebug和远程调试(在phpstorm中使用FTP)

javascript - vue a-href下载不下载

javascript - 在 Javascript 中捕获 Flash Player 事件

javascript - RequireJS - 从页面内部看不到变量

PhpStorm/WebStorm 中的 CoffeeScript JSDoc 支持

intellij-idea - 在PhpStorm项目工具窗口中显示.idea文件夹