[TOC]
  • 入门使用下载添加到项目中编写代码

入门使用

还是先看官网: requirejs.org,中间就有一个getting start, 点击开始入门。

下载

要先使用,先要搭建环境,对于javascript文件,下载即可。进入GET REQUIREJS下载最新版本的requireJS文件。

在下载页面,还有其他几个文件:

  • r.js: 优化,压缩文件的工具
  • text: 加载文本文件的插件
  • domReady: 确保文件在domReady后执行的插件
  • cs: 支持CoffeeScript的插件
  • i18n: 多语言版本支持的插件添加到项目中

下面的例子假设所有的文件都在script目录下,目录结构为:

project-directory/    project.html    scripts/        main.js    helper/        util.js

把requireJS加入到script目录下:

project-directory/    project.html    scripts/        main.js        require.js    helper/        util.js

接下来,在中或者之前,插入:

<!-- data-main attribute tells require.js to load    scripts/main.js after require.js loads. --><script data-main="scripts/main" src="scripts/require.js"></script>

data-main指出的脚本文件,是异步加载的。我们这里的main就是script/main.js文件,里面内容可以如下:

require(["helper/util"], function(util) {    //This function is called when scripts/helper/util.js is loaded.    //If util.js calls define(), then this function is not fired until    //util's dependencies have loaded, and the util argument will hold    //the module value for "helper/util".});

这里提一下require和define的区别:

  • require的依赖只要自身加载完成,就会调用
  • define定义的,所有依赖都加载完了才会被触发编写代码

真正详细的入门,其实在Require API。

但是一般而言,会在data-mian的文件中,写入配置文件,类似:

require.config({    /* global metadata */    baseUrl: './',    waitSeconds: 0,    paths: {        'domReady': 'bower_components/domReady/domReady',        'modernizr': 'bower_components/modernizr/modernizr',        "jquery": "bower_components/jquery/dist/jquery",        'jquery.easing': 'bower_components/jquery.easing/js/jquery.easing'    },    shim: {        'jquery.easing': ['jquery']    },    packages: [{        name: 'gsap',        main: '',        location: 'bower_components/gsap/src/uncompressed'    }]});

原文: https://leohxj.gitbooks.io/front-end-database/content/javascript-modules/requirejs/requirejs-intro.html