RequireJS Module name “requirejs” has not been loa

2019-09-08 16:48发布

I know there is a help page for a module not loading, however, this seems like a different case due to the fact that requirejs cannot find requirejs.

I installed all of my dependencies using npm. My main script is in the project root, which is called by an html page.

Here is a snippet from the web page:

<script type="text/javascript" data-main="./airportLeafletScript.js" src="node_modules/requirejs/require.js"></script>

And then the header of airportLeafletScript.js looks like this:

var requirejs = require('requirejs');

requirejs.config({
//Pass the top-level main.js/index.js require
//function to requirejs so that node modules
//are loaded relative to the top-level JS file.
nodeRequire: require
});

requirejs(['turf', 'jquery', 'leaflet', 'leaflet-rotatedmarker', 
    'leaflet-slider', 'shpjs', 'jquery-ui', 'json3', 'esri-leaflet'],
    function   (turf, $, L, Marker, SliderControl, shp) {
 //foo and bar are loaded according to requirejs
 //config, but if not found, then node's require
 //is used to load the module.
});

The actual error message is:

11:03:19.078 Error: Module name "requirejs" has not been loaded yet for context: _. Use require([])
http://requirejs.org/docs/errors.html#notloaded
makeError() require.js:168
localRequire() require.js:1433
requirejs() require.js:1794
<anonymous> airportLeafletScript.js:46
1 require.js:168:17

So how can I get requirejs working for this project? It doesn't seem to be configured properly

1条回答
姐就是有狂的资本
2楼-- · 2019-09-08 17:06

The code you are showing that does var requirejs = require('requirejs'); is meant to be run in Node.js, not in a browser. Also note the configuration passed to requirejs.config which includes nodeRequire, which only makes sense in Node.js.

When you load that code in a browser with the script tag that you show, RequireJS is already loaded, and the require call tries to load it again, which is bad no matter how you cut it. It happens to trigger a RequireJS-specific error but that's a side-effect of trying to load code written for Node.js through RequireJS.

When you load the same code in Node.js, the require call is handled by Node.js. It load RequireJS and then you can configure it and use it.

查看更多
登录 后发表回答