Search code examples
javascriptnginxrequirejs

Can not get the js file in using requirejs


I'm trying to build client project using requireJs. But when I published it on the nginx server, an error occurred. This is my project directory structure

when it ran here, the browser threw a js error.

require(['config/require.conf'], function(){
    'use strict';
    require(['src/common/js/pageloader'], function(pageloader){
        pageloader();
    })
})

js error:

GET http://localhost:8011/src/homepage/config/require.conf.js require.js:1961

It seems like the error occurred because I use the relative path (lack of '/').

However, I add the slash as prefix of directory('/config/require.conf'). As a result, when the browser ran here, requirejs didn't add the suffix ".js" for the js file(config/require.conf.js).

Another error occurred~

 GET http://localhost:8011/config/require.conf 404 (Not Found) 

What should I do for the error? Thanks.


Solution

  • You can pass two things in the dependency list of a require call:

    • A module name. This is the default. When you pass a module name, RequireJS will convert the name to a path using baseUrl, paths, map, etc. from your RequireJS configuration.

    • A path. RequireJS considers that you are passing a path if the dependency: a) begins with '/', (which is your case), b) contains an HTML query (e.g. 'foo?bar=1'), c) ends with the .js extension, d) specifies a protocol (e.g. https://).

      In this case, RequireJS uses the path as-is, without using its configuration to transform it, and it does not automatically add a .js extension to it.

    Your usage is the 2nd case so you have to add .js to your path so that RequireJS can find your file:

    require(['/config/require.conf.js'], function() {