Pass options to ES6 module imports

后端 未结 7 1136
[愿得一人]
[愿得一人] 2020-11-22 04:43

Is it possible to pass options to ES6 imports?

How do you translate this:

var x = require(\'module\')(someoptions);

to ES6?

7条回答
  •  隐瞒了意图╮
    2020-11-22 05:20

    Concept

    Here's my solution using ES6

    Very much inline with @Bergi's response, this is the "template" I use when creating imports that need parameters passed for class declarations. This is used on an isomorphic framework I'm writing, so will work with a transpiler in the browser and in node.js (I use Babel with Webpack):

    ./MyClass.js

    export default (Param1, Param2) => class MyClass {
        constructor(){
            console.log( Param1 );
        }
    }
    

    ./main.js

    import MyClassFactory from './MyClass.js';
    
    let MyClass = MyClassFactory('foo', 'bar');
    
    let myInstance = new MyClass();
    

    The above will output foo in a console

    EDIT

    Real World Example

    For a real world example, I'm using this to pass in a namespace for accessing other classes and instances within a framework. Because we're simply creating a function and passing the object in as an argument, we can use it with our class declaration likeso:

    export default (UIFramework) => class MyView extends UIFramework.Type.View {
        getModels() {
            // ...
            UIFramework.Models.getModelsForView( this._models );
            // ...
        }
    }
    

    The importation is a bit more complicated and automagical in my case given that it's an entire framework, but essentially this is what is happening:

    // ...
    getView( viewName ){
        //...
        const ViewFactory = require(viewFileLoc);
        const View = ViewFactory(this);
        return new View();
    }
    // ...
    

    I hope this helps!

提交回复
热议问题