RequireJS Module name “requirejs” has not been loaded yet for context. use require([])

蹲街弑〆低调 提交于 2019-12-12 02:37:59

问题


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:


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.



来源:https://stackoverflow.com/questions/38355903/requirejs-module-name-requirejs-has-not-been-loaded-yet-for-context-use-requi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!