- // foo.js
- define(function() {
- const name = "why"
- const age = 18
- function sum(num1, num2) {
- return num1 + num2
- }
- return {
- name,
- age,
- sum
- }
- })
- // bar.js
- define(["foo"], function(foo) {
- console.log("bar:", foo)
- const name = "bar"
- return { name }
- })
- define(["a", "b", "c", "d", "e", "f"], function(a, b, c, d, e, f) {
- // 等于在最前面声明并初始化了要用到的所有模块
- if (false) {
- // 即便没用到某个模块 b,但 b 还是提前执行了
- b.foo()
- }
- });
- // 定义模块 math.js
- define(function(require, exports, module) {
- var a = require('./a'); //遇到require语句时,才会执行对于模块的代码
- a.doSomething();
- if (false) {
- var b = require('./b'); // 该语句不会执行,所以./b对应的模块也不会执行
- b.doSomething();
- }
- let add = function(a,b){
- return a+b;
- }
- exports.add = add; // 导出add
- });
- // 加载模块
- seajs.use(['math.js'], function(math){
- var sum = math.add(1+2);
- });
参考: