Skip to content

seajs-wrap 中文文档 #1

@afc163

Description

@afc163

CommonJS 包装插件

在新的 spm3 中,编码书写规范从 CMD 规范全面转向了 CommonJS 。这样可能会碰到一个问题,在线下调试环境中可以直接运行的 CMD 模块,现在由于去掉了 define 块包装,无法在 Sea.js 环境中直接跑起来。

我们推荐使用 spm doc watch 并打开 http://127.0.0.1:8000 进行调试,这个工具会在本地启动一个静态服务,监听加载的静态文件并动态包装 define 块。

但是这个工具并不能满足所有情况,所以就有了这个插件,可以帮助你对 CommonJS 模块进行调试。首先需要引入 Sea.js(2.1及以上版本) 和插件:

<script src="path/to/sea.js"></script>
<script src="path/to/seajs-wrap.js"></script>

加载 CommonJS 模块

seajs.userequire 来调用 CommonJS 模块。

seajs.use('common', function(Common) {
  // Common 可用了
});
// common.js 是一个 CommonJS 模块,无须手写 define 块
var a = 1;
var b = 2;

module.exports = function () {
  return a + b;
};

seajs-wrap 的实现原理是通过 XHR 对象去加载模块文件,拿到文件内容后动态包装上 define(function(require, exports, module) {}); 块后,再进行执行。拿到文件内容后会进行简单的判断,如果模块已经是 CMD 模块,则不进行包装。

对于不希望进行包装的文件,可以使用 ?nowrap 来指定此模块无须进行包装。

// no-need-to-wrap.js
// 执行前不会进行包装
seajs.use('no-need-to-wrap.js?nowrap', function() {
});

注意事项

  1. seajs-wrap 会通过 XHR 来加载模块(这样才能任意修改源码后执行),所以受到同源策略限制,请务必在线下调试环境来使用这个插件。
  2. seajs-wrap 只针对 JS 模块进行包装。

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions