网络工作者中的RequireJS

isa*_*000 9 javascript web-worker requirejs

我正在尝试在Web worker中使用RequireJS.问题是我在使用它时不断收到以下错误.Uncaught Error: importScripts failed for underscore at ./lib/underscore.js

我已经测试了我的配置选项,它们只在导入Underscore时导致此错误.他们来了:

{
    baseUrl: './',
    paths: {
        jquery: 'lib/jquery',
        underscore: 'lib/underscore'
    },
    shim: {
        underscore: {
            exports: '_'
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如有必要,我可以添加更多信息.该项目的源代码在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'
            }
     }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

require是否通过使用正确加载到 Worker 中importScripts

importScripts('path/to/require.js');

require({ ... });
Run Code Online (Sandbox Code Playgroud)

require repo 中测试是一个很好的示例,另请参阅 Chad 在How to use Web Workers into a Module build with Requirejs 中的回答?

Web worker 有一个专用的全局作用域。问题很可能是因为 Underscore 直到 1.6.0 版(2014 年 2 月,在您发布问题之后才使用 AMD)而加剧。

我强烈建议按照本杰明对您的原始问题的评论所建议的那样使用importScripts()( MDN )。

标准定义可以在https://html.spec.whatwg.org/multipage/workers.html#importing-scripts-and-libraries找到

您为确保跨不同平台的require所有库工作而webWorkers遇到的麻烦不值得这种便利,而且性能方面不会受到任何影响,因为工作人员不会影响您的主应用程序的性能。