我正在尝试在 Web Worker 中使用 RequireJS。问题是我在使用它时不断收到以下错误。 Uncaught Error :importScripts 在 ./lib/underscore.js 下划线失败
我已经测试了我的配置选项,它们只在导入 Underscore 时导致这个错误。他们在这里:
{
baseUrl: './',
paths: {
jquery: 'lib/jquery',
underscore: 'lib/underscore'
},
shim: {
underscore: {
exports: '_'
}
}
}
如有必要,我可以添加更多信息。该项目的源代码位于 GitHub 上 https://github.com/isaach1000/canvas .
更新: 修复 RequireJS 仍然没有成功,但我使用 Grunt 任务修复了我的问题。这是配置:
requirejs: {
worker: {
options: {
baseUrl: 'js',
name: 'task',
out: 'build/task.js',
paths: {
jquery: 'lib/jquery',
underscore: 'lib/underscore'
},
shim: {
underscore: {
exports: '_'
}
},
include: ['lib/require.js'],
optimize: 'none'
}
}
}
最佳答案
您是否使用 importScripts
将 require
正确加载到 Worker 中?
importScripts('path/to/require.js');
require({ ... });
test in the require repo是一个很好的例子,另请参阅 Chad 在 How to use Web Workers into a Module build with Requirejs? 中的回答
网络 worker 有一个 dedicated global scope . Underscore 直到版本 1.6.0( February 2014 ,在您发布问题后)才使用 AMD,这很可能加剧了这个问题。
我强烈建议使用 importScripts()
( MDN ),正如本杰明对您的原始问题的评论所建议的那样。
标准定义可以在 https://html.spec.whatwg.org/multipage/workers.html#importing-scripts-and-libraries 找到
确保 require
适用于跨不同平台的 webWorkers
中的所有库所带来的麻烦是不值得的,而且在性能方面它不会受到任何影响因为工作人员不会影响您的主应用程序的性能。
关于javascript - Web Worker 中的 RequireJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20863527/