首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >混淆RequireJS模块名称

混淆RequireJS模块名称
EN

Stack Overflow用户
提问于 2015-03-18 01:17:18
回答 1查看 518关注 0票数 0

我的项目布局是:

代码语言:javascript
复制
-bin\
    -out.closeure.js // (compiled from out.js using the closure compiler)
    -out.js // this is the requirejs output file, no minification done)
-src\
    -lib\
        -library.js
    -main.js
    -somefile.js

现在,当我使用RequireJS将我的项目合并到一个文件中时,有没有一种方法可以修改模块的名称?例如,在main.js中而不是:

代码语言:javascript
复制
require(['somefile'], function(SomeFile){
    //blah
});

我要一份

代码语言:javascript
复制
require(['a6fa7'], function(SomeFile){
    //blah
});

因为我使用闭包编译器来混淆所有的东西,所以唯一没有被混淆的就是模块名称,我也想去混淆它。

我看了看https://github.com/stevensacks/grunt-requirejs-obfuscate插件,但它不工作,我不确定这个插件是否能做我想要的。

EN

回答 1

Stack Overflow用户

发布于 2015-12-06 10:42:32

Edit1:我鼓励使用AMDclean,可能没有理由将内存占用和生产保持在优化的构建上。如果你想保留它,下面的方法是我所做的变通方法:使用onBuildWriteonBuildRead,正如文档所述:onBuildWrite一个函数,每次写入优化的模块包时都会调用该函数。这允许在序列化之前对内容进行转换。

代码语言:javascript
复制
"replaceModuleNames": [],
//executed on every file read
onBuildRead: function(moduleName, path, contents){
    this["replaceModuleNames"].push({
        "name": moduleName,
        "with": makeid()
    });
    //Always return a value.
    return contents;
},
onBuildWrite: function (moduleName, path, contents) {
    console.log("moduleName: " + moduleName + " ,path: " + path + " ,contents: ... ");
    var text = contents;
    RegExp.escape = function(text) {
        return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    };
    this["replaceModuleNames"].forEach(function(element){
        var regE = new RegExp('(?:define\\(|require\\().*(?:"|\')('+RegExp.escape(element["name"])+')(?:"|\')');
        text = text.replace(regE, function(a, b){
            return a.replace(b, element["with"]);
        });
        console.log("moduleName: "+moduleName+ " replaceWith: " + element["with"] + " result: " + text);
    });
    //Always return a value.
    return text;
}

把它放在build.js上,你必须实现makeid方法,我测试了它,但它可能会失败,所以不要依赖它来生产

Edit2:text.replace(element["name"], element["with"]);可能会导致不一致的代码,用正则表达式组替换,我没有使用正则表达式的经验,所以它可以改进。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29105578

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档