ES6 모듈을 조건부로 가져 오려면 어떻게해야합니까?
나는 다음과 같은 일을해야합니다 :
if (condition) {
import something from 'something';
}
// ...
if (something) {
something.doStuff();
}
위의 코드는 컴파일되지 않습니다. 던졌습니다 SyntaxError: ... 'import' and 'export' may only appear at the top level
.
여기 에 System.import
표시된대로 사용하려고했지만 어디서 왔는지 모르겠습니다 . ES6 제안은 결국 받아 들여지지 않았습니까? 이 기사의 "프로그래밍 API"링크는 더 이상 사용되지 않는 문서 페이지로 덤프 합니다 .System
이제 ECMA와 함께 동적 수입 제안이 있습니다. 3 단계 입니다. babel-preset 으로도 제공됩니다 .
다음은 귀하의 경우에 따라 조건부 렌더링을 수행하는 방법입니다.
if (condition) {
import('something')
.then((something) => {
console.log(something.something);
});
}
이것은 기본적으로 약속을 반환합니다. 약속의 해결은 모듈을 가질 것으로 예상됩니다. 제안서에는 여러 동적 가져 오기, 기본 가져 오기, js 파일 가져 오기 등과 같은 다른 기능도 있습니다 . 동적 가져 오기 에 대한 자세한 정보는 여기를 참조하십시오 .
원하는 경우 require를 사용할 수 있습니다. 이것은 조건부 require 문을 갖는 방법입니다.
let something = null;
let other = null;
if (condition) {
something = require('something');
other = require('something').other;
}
if (something && other) {
something.doStuff();
other.doOtherStuff();
}
조건부로 가져올 수는 없지만 반대로 할 수 있습니다. 조건부로 무언가를 내 보냅니다. 사용 사례에 따라 다르므로이 해결 방법이 적합하지 않을 수 있습니다.
넌 할 수있어:
api.js
import mockAPI from './mockAPI'
import realAPI from './realAPI'
const exportedAPI = shouldUseMock ? mockAPI : realAPI
export default exportedAPI
apiConsumer.js
import API from './api'
...
I use that to mock analytics libs like mixpanel, etc... because I can't have multiple builds or our frontend currently. Not the most elegant, but works. I just have a few 'if' here and there depending on the environment because in the case of mixpanel, it needs initialization.
Looks like the answer is that, as of now, you can't.
http://exploringjs.com/es6/ch_modules.html#sec_module-loader-api
I think the intent is to enable static analysis as much as possible, and conditionally imported modules break that. Also worth mentioning -- I'm using Babel, and I'm guessing that System
is not supported by Babel because the module loader API didn't become an ES6 standard.
require()
is a way to import some module on the run time and it equally qualifies for static analysis like import
if used with string literal paths. This is required by bundler to pick dependencies for the bundle.
const defaultOne = require('path/to/component').default;
const NamedOne = require('path/to/component').theName;
For dynamic module resolution with complete static analysis support, first index modules in an indexer(index.js) and import indexer in host module.
// index.js
export { default as ModuleOne } from 'path/to/module/one';
export { default as ModuleTwo } from 'path/to/module/two';
export { SomeNamedModule } from 'path/to/named/module';
// host.js
import * as indexer from 'index';
const moduleName = 'ModuleOne';
const Module = require(indexer[moduleName]);
obscuring it in an eval worked for me, hiding it from the static analyzer ...
if (typeof __CLI__ !== 'undefined') {
eval("require('fs');")
}
I was able to achieve this using an immediately-invoked function and require statement.
const something = (() => (
condition ? require('something') : null
))();
if(something) {
something.doStuff();
}
Conditional imports could also be achieved with a ternary and require()
s:
const logger = DEBUG ? require('dev-logger') : require('logger');
This example was taken from the ES Lint global-require docs: https://eslint.org/docs/rules/global-require
Look at this example for clear understanding of how dynamic import works.
Dynamic Module Imports Example
To have Basic Understanding of importing and exporting Modules.
참고URL : https://stackoverflow.com/questions/36367532/how-can-i-conditionally-import-an-es6-module
'IT' 카테고리의 다른 글
C #에 매개 변수 제약 조건이있는 일반 생성자가 있습니까? (0) | 2020.06.07 |
---|---|
Apache Commons equals / hashCode 빌더 (0) | 2020.06.07 |
std :: vector가 push_back으로 객체를 복사합니까? (0) | 2020.06.07 |
wait () 호출시 IllegalMonitorStateException (0) | 2020.06.07 |
펑크 (0) | 2020.06.07 |