将选项传递给ES6模块导入

2020/11/11 10:22 · javascript ·  · 0评论

是否可以将选项传递给ES6导入?

您如何翻译此:

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

到ES6?

用单个import语句无法做到这一点,它不允许调用。

因此,您不会直接调用它,但基本上可以执行与commonjs默认导出相同的操作:

// module.js
export default function(options) {
    return {
        // actual module
    }
}

// main.js
import m from 'module';
var x = m(someoptions);

另外,如果您使用支持单价承诺的模块加载器,则可以执行类似

System.import('module').ap(someoptions).then(function(x) {
});

有了新的import运营商,它可能会变成

const promise = import('module').then(m => m(someoptions));

要么

const x = (await import('module'))(someoptions)

但是,您可能不希望动态导入,而希望静态导入。

概念

这是我使用ES6的解决方案

这与@Bergi的响应非常一致,这是我在创建需要传递用于class声明的参数的导入时使用的“模板” 这是在我正在编写的同构框架上使用的,因此可以在浏览器和node.js(我Babel与一起使用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();

上面将foo在控制台中输出

编辑

现实世界的例子

对于一个真实的示例,我正在使用它来传递名称空间,以访问框架中的其他类和实例。因为我们只是创建一个函数并将对象作为参数传递,所以可以将其与类声明一起使用,如下所示:

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

导入有点复杂,automagical就我而言,它是一个完整的框架,但实际上这是正在发生的事情:

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

I hope this helps!

Building on @Bergi's answer to use the debug module using es6 would be the following

// original
var debug = require('debug')('http');

// ES6
import * as Debug from 'debug';
const debug = Debug('http');

// Use in your code as normal
debug('Hello World!');

I believe you can use es6 module loaders.
http://babeljs.io/docs/learn-es6/

System.import("lib/math").then(function(m) {
  m(youroptionshere);
});

You just need to add these 2 lines.

import xModule from 'module';
const x = xModule('someOptions');

I've landed on this thread looking up for somewhat similar and would like to propose a sort of solution, at least for some cases (but see Remark below).

Use case

I have a module, that is running some instantiation logic immediately upon loading. I do not like to call this init logic outside the module (which is the same as call new SomeClass(p1, p2) or new ((p1, p2) => class SomeClass { ... p1 ... p2 ... }) and alike).

I do like that this init logic will run once, kind of a singular instantiation flow, but once per some specific parametrized context.

Example

service.js has at its very basic scope:

let context = null;                  // meanwhile i'm just leaving this as is
console.log('initialized in context ' + (context ? context : 'root'));

Module A does:

import * as S from 'service.js';     // console has now "initialized in context root"

Module B does:

import * as S from 'service.js';     // console stays unchanged! module's script runs only once

So far so good: service is available for both modules but was initialized only once.

Problem

How to make it run as another instance and init itself once again in another context, say in Module C?

Solution?

This is what I'm thinking about: use query parameters. In the service we'd add the following:

let context = new URL(import.meta.url).searchParams.get('context');

Module C would do:

import * as S from 'service.js?context=special';

the module will be re-imported, it's basic init logic will run and we'll see in the console:

initialized in context special

Remark: I'd myself advise to NOT practice this approach much, but leave it as the last resort. Why? Module imported more than once is more of an exception than a rule, so it is somewhat unexpected behavior and as such may confuse a consumers or even break it's own 'singleton' paradigms, if any.

Here's my take on this question using the debug module as an example;

On this module's npm page, you have this:

var debug = require('debug')('http')

In the line above, a string is passed to the module that is imported, to construct. Here's how you would do same in ES6


import { debug as Debug } from 'debug'
const debug = Debug('http');


Hope this helps someone out there.

本文地址:http://javascript.askforanswer.com/jiangxuanxiangchuandigeies6mokuaidaoru.html
文章标签: ,   ,   ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!