本文介绍了RequireJS不遵循baseUrl set的data-main的相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用requireJS,我试图为我的data-main指定一个与baseUrl不同的路径。似乎requireJS忽略了我在文件名之前输入的内容,并且总是在baseUrl文件夹中查找该文件。

Using requireJS, I am trying to specify a path for my data-main that is different from the baseUrl. It seems that requireJS is ignoring whatever I type before the file name, and always look for the file in the baseUrl folder.

我有以下文件夹结构:

index.html
scripts/
  lib/
    require.js
  test/
    main2.js
  config.js

index.html的内容:

Contents of index.html :

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Test</title>
        <script data-main="test/main2" src="scripts/lib/require.js"></script>
        <script src="scripts/config.js"></script>
    </head>

    <body></body>
</html>

config.js的内容:

Contents of config.js :

requirejs.config({
    baseUrl: "scripts"
});

我收到404错误:GET [...] / scripts / main2.js ,即使它应该寻找[...] / scripts / test / main2.js。如果我删除config.js文件并使用data-main =scripts / test / main2它可以工作,但我希望能够为我的项目指定一个baseUrl。

And I am getting a 404 error for : GET [...]/scripts/main2.js , even though it should be looking for [...]/scripts/test/main2.js. If I remove the config.js file and use data-main="scripts/test/main2" it works, but I would like to be able to specify a baseUrl for my project.

任何想法?

编辑:按照Waxen的回答:

Edit : following the answer by Waxen :


  • 即使我在我的data-main中使用scripts / test / main2,/ scripts / test / main2或whateverIWant / main2,奇怪的是总是寻找scripts / main2.js

请注意,我使用的是requirejs 2.1.8

Note that I am using requirejs 2.1.8

推荐答案

这不符合您的要求,因为在设置baseURL之前,您需要使用data-main调用require。我不知道为什么它会尝试去script / main2.js;我希望它尝试加载test / main2.js而不是scripts / main2.js。然而,这不是重点。

This isn't working how you want it to because you're calling require with a data-main before you're setting the baseURL. I'm not sure why it's trying to go to scripts/main2.js though; I would expect it to attempt to load test/main2.js rather than scripts/main2.js. However, that's beside the point.

您需要做的是在尝试加载data-main之前确保您的baseURL可用。这可以通过首先包含您的配置并使用第二个示例中的语法来实现:。

What you need to do is make sure that your baseURL is available to require before it tries to load you data-main. This can be accomplished by including your config first and using the syntax from the second example here: http://requirejs.org/docs/api.html#config.

index.html的内容:

Contents of index.html :

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Test</title>
        <script src="scripts/config.js"></script>
        <script data-main="test/main2" src="scripts/lib/require.js"></script>
    </head>

    <body></body>
</html>

config.js的内容:

Contents of config.js :

var require = {
    baseUrl: "scripts"
};

这篇关于RequireJS不遵循baseUrl set的data-main的相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 13:24