简体   繁体   English

使用es6导入未定义erorr

[英]import is not defined erorr using es6

I try to follow a tutorial here. 我尝试在这里遵循教程。 I have babel installed, but I couldn't detect what mistake I done below 我已经安装了通天塔,但是我无法检测到我在下面犯了什么错误

sum.js sum.js

export default sum = (a, b) => {
    return a + b;
}

sum.test.js sum.test.js

import sum from './sum';

test('1 + 2 should equal to 3', () => {
    expect(sum(1,2)).toBe(3);
});

the error is sum is not defined in sum.test.js. 错误是sum未在sum.test.js中定义。 2 files are placed within the same level of directory. 2个文件放置在同一级别的目录中。

I think, issue is you forgot to define sum in sum.js , Write it like this: 我认为,问题是您忘记在sum.js定义sum ,应sum.js编写:

let sum;
export default sum = (a, b) => {
    return a + b;
}

or 要么

let sum = (a, b) => {
    return a + b;
}

export default sum;

Note : In case of default export you can remove the name, because default export will be only one per file. 注意 :如果使用default export ,则可以删除名称,因为default export每个文件只有一个。 At the time of importing you can use any name, like this: 导入时,您可以使用任何名称,例如:

import ABC from './sum';

Update : 更新

There are two ways of defining a function: 定义函数有两种方法:

1: function sum(){}
2: var sum = function(){}

So if you use first one then export it directly(no need of defining): 因此,如果您使用第一个,然后直接将其导出(无需定义):

export default sum(){}

but if you use second one then you need to define the variable because you are storing the function definition in that variable: 但是如果使用第二个,则需要定义变量,因为您将函数定义存储在该变量中:

let sum;

export default sum = () => {}

or 要么

let sum = () => {}

export default sum;

Check this article: https://danmartensen.svbtle.com/build-better-apps-with-es6-modules 检查本文: https : //danmartensen.svbtle.com/build-better-apps-with-es6-modules

You need to declare sum before using in export 您需要在出口中使用之前声明总和

like var sum; 像var sum;

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

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