es6-module默认导出导入为undefined [英] es6-module default export importing as undefined

查看:720
本文介绍了es6-module默认导出导入为undefined的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定我在这里缺少什么。我正在使用jspm和es6-module-loader开发一个项目。我有一个模块定义如下:

I'm not sure what I'm missing here. I'm working on a project using jspm and es6-module-loader. I've got an module defined as follows:

import hooks from './hooks';
import api from './api';
import tools from './tools';

const StencilUtils = {
    hooks: hooks,
    api: api,
    tools: tools,
};

export {hooks, api, tools};
export default StencilUtils;

/* global define */
(function(root) {
    if (typeof define === 'function' && define.amd) {
        define(function() {
            return (root.stencilUtils = StencilUtils);
        });
    } else if (typeof module === 'object' && module.exports) {
        module.exports = StencilUtils;
    } else {
        window.stencilUtils = StencilUtils;
    }
}(this));

我在另一个文件中导入此模块,并按如下方式使用它:

I'm importing this module in another file, and using it like so:

import utils from 'bigcommerce/stencil-utils';

utils.hooks.on('cart-item-add', (event, form) => {
    // do stuff
});

当文件加载时,我收到 utils undefined 。如果我将文件更改为:

When the files load, I get an error that utils is undefined. If I change the file to this:

import {hooks} from 'bigcommerce/stencil-utils';

hooks.on('cart-item-add', (event, form) => {
    // do stuff
});

它正常工作。因此,使用默认导出语句似乎无法正常工作。导入此问题的导入或导出语句是否存在明显错误?

It works correctly. So, it appears something is not working correctly with the default export statement. Is there something obviously wrong here with the import or export statements that would cause this issue?

推荐答案

我认为有两件事情这个问题:

I think there are two things around this issue:


  1. 当您命名导出时,您可以通过导入为库或使用对象销毁来访问它们。

方法1

xyz.js

export const a = 1;

abc.js

import {a} from "xyz";

方法2

xyz.js

export const a = 1;

abc.js

import {* as myModule} from "xyz";
console.log(myModule.a);

所以在你的情况下

export {hooks, api, tools};

它可以是

import * as utils from 'bigcommerce/stencil-utils';

import {hooks} from 'bigcommerce/stencil-utils';




  1. 默认导出声明不正确

它可以是

export default {
    hooks: hooks,
    api: api,
    tools: tools,
};

const StencilUtils = {
   hooks: hooks,
   api: api,
   tools: tools,
};
export { StencilUtils as default };

希望这会对你有所帮助。有关详细信息,请参阅

Hope this will help you. For more details see this

这篇关于es6-module默认导出导入为undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆