简体   繁体   English

导入CommonJS不能在ES6中正确解构

[英]Importing CommonJS does not destructure correctly in ES6

In the root of my module dependency I have a file called form.js : 在模块依赖项的根目录中,有一个名为form.js的文件:

module.exports = require("./dist/bundle.js").form;

In my project I have: 在我的项目中,我有:

import { someComponent } from 'my-dependency/form';

Yet someComponent will be undefined . 然而someComponent将是undefined

If I do this: 如果我这样做:

import form from 'my-dependency/form';
console.log(form.someComponent);

It will output something that looks like this in the console: 它将在控制台中输出如下所示的内容:

ƒ Rr(e){var t=e.component,n=void 0===t?"input":t,r=e.rend[....]

Yet, if I do this, it will work: 但是,如果我这样做,它将起作用:

import form from 'my-dependency/form';
const { someComponent } = form;

What am I doing wrong here and how might I achieve what I want? 我在这里做错了什么,我怎么能实现我想要的?

Inside of my src/form.js file I have: 在我的src/form.js文件中,我具有:

import someComponent from "./someComponent";
export default {
  someComponent
};

Inside of src/index.js , I have: src/index.js里面,我有:

import * as form from "./form";
export default {
  form
};

Probable root cause but not sure how to fix?... 可能是根本原因,但不确定如何解决?

It looks like the problem caused by exporting with CommonJS and importing using the ES6 syntax. 看起来是由CommonJS导出并使用ES6语法导入引起的问题。

Here is someone with a similar issue but from 4 years ago: https://github.com/google/traceur-compiler/issues/1483 这是一个有类似问题的人,但来自4年前: https//github.com/google/traceur-compiler/issues/1483

and, from 2 years ago: https://github.com/Microsoft/TypeScript/issues/11179 并且,从2年前开始: https : //github.com/Microsoft/TypeScript/issues/11179

I've tried explicitly setting code like so but this did not seem to achieve what I want (creates a module with a default property): 我已经尝试过像这样显式设置代码,但这似乎没有实现我想要的(创建带有默认属性的模块):

Object.defineProperty(module.exports, "__esModule", {
  value: true
});

It looks like reading online people will do import * as whatever from '..' but shouldn't destructuring work too?... 看起来在线阅读人们会import * as whatever from '..'但也不应破坏工作吗?...

Two ways, either: 有两种方式:

export const someComponent

Then: 然后:

import { someComponent } from 'my-dependency/form'

Or: 要么:

export default {
  someComponent
}

Then: 然后:

import someComponent from 'my-dependency/form'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM