Home  >  Article  >  Web Front-end  >  How to solve the problem of seajs module compression

How to solve the problem of seajs module compression

小云云
小云云Original
2018-01-26 10:31:57957browse

在优化整理项目代码时,想使用seajs来把代码模块化。看了下官方5分钟上手教程,觉得很不错,也没多想就一直开发下去了,也没出什么问题。等一同事说把代码打包个放到设备上去测试一下,发现怎么也跑不起来,郁闷了。于是单步调试一把,发现模块一直加不进来。看了一下seajs的原码,明白了是怎么回事。

define模块解析依赖有两种途径,一种是从define(id, deps, factory)中的deps来;还有一种是解析define代码,从require中来。来看一下代码:


Module.define = function (id, deps, factory) {
 var argsLen = arguments.length
 // define(factory)
 if (argsLen === 1) {
  factory = id
  id = undefined
 }
 else if (argsLen === 2) {
  factory = deps
  // define(deps, factory)
  if (isArray(id)) {
   deps = id
   id = undefined
  }
  // define(id, factory)
  else {
   deps = undefined
  }
 }
 // Parse dependencies according to the module factory code
 if (!isArray(deps) && isFunction(factory)) {
  deps = parseDependencies(factory.toString())
 }
 ...

如果传了deps那就不进行解析了,如果传那就进行源码解析:


var REQUIRE_RE = /"(?:\\"|[^"])*"|'(?:\\'|[^'])*'|\/\*[\S\s]*?\*\/|\/(?:\\\/|[^\/\r\n])+\/(?=[^\/])|\/\/.*|\.\s*require|(?:^|[^$])\brequire\s*\(\s*(["'])(.+?)\1\s*\)/g
var SLASH_RE = /\\\\/g
function parseDependencies(code) {
 var ret = []
 code.replace(SLASH_RE, "")
   .replace(REQUIRE_RE, function(m, m1, m2) {
    if (m2) {
     ret.push(m2)
    }
   })
 return ret
}

seajs是对源码正则对比,查找require,也就是说require在seajs模块中,是一个关键字。

那么问题就来了,一般我们使用的压缩工具都变量进行压缩,require不是标准的js关键字,所以经过一压缩require就变成了abcdefg....所以自然就无法使用了。

解析办法有两个:

1. seajs官方给出是seajs标准模块构建工具:https://github.com/seajs/seajs/issues/538 使用spm进行构建。

2. 更换压缩工具,使用一个可以自定义关键字,也就是让压缩工具不压缩require变量。

目前主流的三个压缩工具:YUI Compressor,Google Closure Compiler,UglifyJS。就目前所知,貌似前两个都不支持自定义关键字(?),UglifyJS是支持的。所以可以使用UglifyJS进行压缩


UglifyJS hello.js -o hello.min.js -m -c -r require

通过-r选项来指定变量不压缩。

总的来说使用seajs应该尽量的去使用官方的构建工具。

相关推荐:

Python中使用gzip模块压缩文件的简单教程


The above is the detailed content of How to solve the problem of seajs module compression. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn