简体   繁体   中英

Importing CommonJS does not destructure correctly in ES6

In the root of my module dependency I have a file called 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 .

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:

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

Inside of src/index.js , I have:

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.

Here is someone with a similar issue but from 4 years ago: https://github.com/google/traceur-compiler/issues/1483

and, from 2 years ago: 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?...

Two ways, either:

export const someComponent

Then:

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

Or:

export default {
  someComponent
}

Then:

import someComponent from 'my-dependency/form'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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