es6 - import all named module without alias

前端 未结 5 804
执笔经年
执笔经年 2020-12-03 00:11

I know that we can import all named modules with alias as below,

import * as name from \"module-name\";

Ref: https://developer.mozilla.org

5条回答
  •  甜味超标
    2020-12-03 01:11

    Here's a crazy experiment I did, that works, but it's probably dangerous in ways I don't fully understand. Would somebody explain to me why we don't do this?

    var lodash = require("lodash");
    
    function $localizeAll(name) {
        return `eval("var " + Object.getOwnPropertyNames(${name}).reduce((code, prop)=>{
            if (/^[a-zA-Z$_][a-zA-Z$_0-9]*$/.test(prop)) {
                return code.concat(\`\${prop} = ${name}["\${prop}"]\n\`);
            } else {
                console.warn("did not import '" + prop + "'");
                return code;
            }
        }, []).join(", ")+";")`
    }
    
    // this will make all exports from lodash available
    eval($localizeAll("lodash"));
    
    console.log(add(indexOf([1,2,6,7,12], 6), 5)); // => 7
    

    It's a bit complicated as it evals in two levels, but it basically iterates of all the properties of an object with the given name in scope and binds all properties that have names qualified to be identifiers to an identifier by that name:

    var length = lodash["length"]
      , name = lodash["name"]
      , arguments = lodash["arguments"]
      , caller = lodash["caller"]
      , prototype = lodash["prototype"]
      , templateSettings = lodash["templateSettings"]
      , after = lodash["after"]
      , ary = lodash["ary"]
      , assign = lodash["assign"]
      , assignIn = lodash["assignIn"]
      , assignInWith = lodash["assignInWith"]
      , assignWith = lodash["assignWith"]
      , at = lodash["at"]
      , before = lodash["before"]
      , bind = lodash["bind"]
      , bindAll = lodash["bindAll"]
      , bindKey = lodash["bindKey"]
      //...
      , upperCase = lodash["upperCase"]
      , upperFirst = lodash["upperFirst"]
      , each = lodash["each"]
      , eachRight = lodash["eachRight"]
      , first = lodash["first"]
      , VERSION = lodash["VERSION"]
      , _ = lodash["_"]
      ;
    

    There are some examples in this list of why this is a bad idea (e.g. it shadows arguments).

    You should be able to use this as follows (though you probably shouldn't like they say above).

    B.js

    import BaseComponent, * as extras from './A';
    
    eval($localizeAll("extras"));
    
    export default class B extends BaseComponent {}
    

    Anyways, couldn't resist trying this out ;)

提交回复
热议问题