Equivalent of requiring a subproperty in ES6 import

我的梦境 提交于 2019-12-02 04:32:16

问题


I have an existing require:

const {dialog} = require('electron').remote;

I started using Babel for ES6, and would like to import this instead. So far I have:

import electron from 'electron';
const {dialog} = electron.remote;

This is ugly, and I can't help but feel there is a better way to do this. I just need the dialog here. How do I get at it in one line?


回答1:


ECMAScript module syntax doesn't allow deep destructuring. In fact it doesn't destructure at all. Import statements create live bindings between modules.

Here is great blog post written by Ben Nadel. It should shed some light on bindings: http://www.bennadel.com/blog/3131-the-import-statement-creates-a-live-view-of-modules-in-es6-and-typescript-in-angular-2.htm

So by doing

import electron from 'electron';
const {dialog} = electron.remote;

electron is such binding. By doing destructuring assignment dialog is normal constant and it won't be "bound" to electron module (it won't update).




回答2:


There is nothing 'ugly', it is how the things should be written in ES6.

imports are supposed to be statically analyzed without script evaluation, supported syntax is limited. Default import can't be destructured in import statement, all varieties of syntax are listed in the reference.

It can be written as

import electron from 'electron';
const { remote: { dialog } } = electron;


来源:https://stackoverflow.com/questions/39059084/equivalent-of-requiring-a-subproperty-in-es6-import

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!