ES6 모듈 가져 오기에 옵션 전달
옵션을 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);
또는 monadic promise 를 지원하는 모듈 로더를 사용하면 다음과 같은 작업을 수행 할 수 있습니다.
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를 (내가 사용에 transpiler와 함께 작동합니다 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 better, IMHO, at least in some cases, solution (or hear why it is not so).
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
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.
참고URL : https://stackoverflow.com/questions/29923879/pass-options-to-es6-module-imports
'Programming' 카테고리의 다른 글
어떤 iomanip 조작자가 '고정적'입니까? (0) | 2020.07.01 |
---|---|
λ- 미적분 최적 평가자가 공식없이 큰 모듈 식 지수를 계산할 수있는 이유는 무엇입니까? (0) | 2020.07.01 |
AngularJS와 $ http를 동기화하는 방법 (0) | 2020.07.01 |
검정색 배경에 흰색 텍스트로 프로그래밍 하시겠습니까? (0) | 2020.07.01 |
Mac과 Windows에서 Excel로 CSV 파일을 올바르게 여는 인코딩은 무엇입니까? (0) | 2020.07.01 |