RequireJS in web worker

2019-03-26 05:52发布

问题:

I am trying to use RequireJS inside a web worker. The problem is that I keep getting the following error when using it. Uncaught Error: importScripts failed for underscore at ./lib/underscore.js

I have tested my configuration options, and they only cause this error when importing Underscore. Here they are:

{
    baseUrl: './',
    paths: {
        jquery: 'lib/jquery',
        underscore: 'lib/underscore'
    },
    shim: {
        underscore: {
            exports: '_'
        }
    }
}

I can add more info if necessary. The source for this project is on GitHub at https://github.com/isaach1000/canvas.

UPDATE: Still no luck on fixing RequireJS, but I fixed my issue using a Grunt task. Here is the configuration:

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'
            }
     }
}

回答1:

Did you load require properly into the Worker by using importScripts?

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

require({ ... });

The test in the require repo is a pretty good example, also see Chad's answer in How to use Web Workers into a Module build with Requirejs?

Web workers have a dedicated global scope. The problem was most likely exacerbated by Underscore not using AMD until version 1.6.0 (February 2014, after you posted the question).

I would highly recommend using importScripts() (MDN) as suggested by Benjamin's comment on your original question.

The standard definition can be found at https://html.spec.whatwg.org/multipage/workers.html#importing-scripts-and-libraries

The hassle you get for making sure require works for all libs in webWorkers across different platforms is not worth the convenience, and performance wise it doesn't take any hit as workers don't affect the performance of your main app.