RequireJS load string

后端 未结 3 1422
隐瞒了意图╮
隐瞒了意图╮ 2021-02-10 01:47

In my app there are dynamic parts that are loaded from database as string that looks like:

\"define([\'dependency1\', \'dependency2\'], function(){\"+
\"   // fu         


        
3条回答
  •  Happy的楠姐
    2021-02-10 02:03

    To answer the question a little more directly, create a plugin like so:

    define("load-string",[], function(){
        var strings=[],
            re_package_name = /^string_module_(\d+)$/;
        return {
            normalize: function(name, _){
                if(re_package_name.test(name)){
                    return name
                }
                var nml = "string_module_" + (strings.push(name)-1);
                return nml;
            },
            load: function(name, _, onLoad, config){
                if(re_package_name.test(name)){
                    onLoad.fromText(strings[name.match(re_package_name)[1]]);
                }else{
                    onLoad.error("Invalid package name: ",name);
                }
            }  
        }
    });
    

    and use it like so:

    var world_module = "define([],function(){return 'world!'})";
    
    require(["load-string!" + world_module],
        function(x){
            console.log("Hello "+x);
        })
    

提交回复
热议问题