在单个文件中RequireJS多个模块 [英] RequireJS multiple module in single file

查看:328
本文介绍了在单个文件中RequireJS多个模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将多个模块合并到一个文件中,但我找不到关于如何操作的官方文档。现在我使用下面的方法,它有效,但我想知道以下内容:

I want to merge multiple modules into a single file, but I can't find an official document about how to do it. Now I'm using the below method, it works, but I'm wondering about the following:


  • 技术上是否正确?

  • RequireJS如何检查模块是否已加载?通过使用模块名称或文件名?

  • 在某些情况下,此解决方案是否会多次启动模块?

index.html

<script src="require.js"></script>
<script>
requirejs.config({
    paths: {
        'a': 'test',
        'b': 'test'
    }
});

require(['a', 'b'], function () {
    console.log('a & b loaded');
});
</script>

test.js

console.log('loading test.js');
// I have some init here, like "Avoid `console` errors in IE"

define('a', function () {
    console.log('a module');
});

define('b', function () {
    console.log('b module');
});


推荐答案

这已经过时了,但我刚碰到它。
当然你可以在同一个文件中有多个定义,是的,这是有道理的。

This is old but I just bumped into it. Sure you can have multiple define in the same file, and yes, it makes sense.

你唯一需要做的就是使用命名定义。

The only thing you need to do is to use named defines.

define('module1', ['dependency1', 'dependency2'], function (d1, d2) {
    // your code here
}

认为有时你不需要你的资源要动态加载,实际上可能需要在开头加载它们,在打包时创建单个连接/缩小的js文件是最好的解决方案。

Think that sometimes you don't need your resources to be loaded dynamically, having them loaded all at the beginning might actually be required, co creating a single concatenated/minified js file at packaging time is the best solution.

所以您不会利用延迟加载,但您仍然可以使用RequireJS以模块化方式设计您的应用程序。

So you won't take advantage of the "lazy loading" but you still design your app in a modular way by using RequireJS.

这篇关于在单个文件中RequireJS多个模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆