RequireJS 没有加载正确的路径

RequireJS not loading the right path

我正在尝试将 requirejs 改造到一个项目中,但我间歇性地在文件上收到“404 Not Found”。

每大约 3 或 4 次重新加载,我都会收到以下错误

GET http://localhost:8080/build/jquery.js 
Uncaught Error: Script error for: jquery

GET http://localhost:8080/build/touchSwipe.js
Uncaught Error: Script error for: touchSwipe

我的文件如下所示:

config.js

require.config({
    paths: {
        'jquery': 'vendor/jquery',
        'touchSwipe': 'vendor/jquery.touchSwipe.min',
        'scripts': 'scripts/'
    },
    shim: {
        'touchSwipe': {
            deps: ['jquery']
        }
    }
});
require(['main']);

main.js

require(
    ['scripts/menu', 
    .. more js files .. ]);

我使用 g运行t-contrib-requirejs 优化文件,一切似乎都正常

Gruntfile.js

requirejs: {
    compile: {
        options: {
            baseUrl: "path/to/file/",
            mainConfigFile: "path/to/file/config.js",
            dir: 'path/to/build/',
            modules: [
                {
                    name: 'main'
                },
            ],
            uglify: {
                no_mangle: true
            },
        }
    }
}

...只是为了填补空白,我的 main.hbs 文件有这个脚本标签

<script data-main="/build/config" src="/js/vendor/require.js"></script>

正如我所说,在我尝试引入更多模块之前,一切正常。我只想在某些页面上加载的模块。

我尝试通过在相关页面末尾添加以下代码来做到这一点

<script type="text/javascript">
    require(['scripts/page1']);
</script>

page1.js 文件看起来像这样...

define(['jquery', 'touchSwipe'], function ($j) {
    ...
});

没有出现这些错误的时候,站点似乎工作正常。另一件需要注意的事情是,这似乎只有在我通过 G运行t 任务 运行 代码时才会出现。

问题是错误中的 url 是错误的。 jQuery 应该位于 /build/vendor/ 而不是 /build/,而 touchSwipe 是我为库定义的路径。这看起来像是一个时间问题;在新文件之后加载配置。

我想通了

我需要在 Grunt 中指定文件,在模块下,像这样

modules: [
    //First set up the common build layer.
    {
        //module names are relative to baseUrl
        name: 'config',
        include: [
            'jquery',
            'touchSwipe',
            'jquery-ui',
            'modernizr'
        ]
    },
    {
      name: 'scripts/page1',
      exclude: ['config']
    }
],

然后我没有将配置文件添加到脚本标签,而是这样做了

require(['./build/config'], function () {  
    require(['scripts/page1']);
});

我添加了

baseUrl: "build"

到我的配置文件,这似乎已经成功了