Javascript ES6使用导出和导入时出错

Javascript ES6使用导出和导入时出错,javascript,ecmascript-6,Javascript,Ecmascript 6,我想在另一个JS文件中使用该函数,所以我这样做: a、 js b、 js 并在Chrome中运行,但我在Chrome开发工具中遇到一个错误: 承诺类型错误中未捕获:无法读取的属性“test1” 未定义 评估时 我该如何解决这个错误呢? 谢谢。您没有在a.js中导出GotMsg const GotMsg = { test1(key) { console.warn(`It is Test1 + ${key}`); }, test2(key) { console.warn(

我想在另一个JS文件中使用该函数,所以我这样做:

a、 js

b、 js

并在Chrome中运行,但我在Chrome开发工具中遇到一个错误:

承诺类型错误中未捕获:无法读取的属性“test1” 未定义 评估时

我该如何解决这个错误呢?
谢谢。

您没有在a.js中导出GotMsg

const GotMsg = {
  test1(key) {
    console.warn(`It is Test1 + ${key}`);
  },
  test2(key) {
    console.warn(`It is Test2 + ${key}`);
  },
};
export default GotMsg;
然后在b.js中

import GotMsg from './GotMsg'; // or wherever it is

// do things.
另一种导出方法是导出每个单独的函数

export function test1() {}
export function test2() {}
然后


该错误的原因是您没有正确导入它,并且没有导出默认的GotMsg

或者,您可以按如下方式导出:

// a.js
export const GotMsg = {
  test1(key) {
    console.warn(`It is Test1 + ${key}`);
  },
  test2(key) {
    console.warn(`It is Test2 + ${key}`);
  },
};

// b.js
import { GotMsg } from './scripts/a';

就是这样,如果您以前没有导出^^^哦,您就无法导入代码包!我不知道为什么它不显示。我只需键入导出默认值{GotMsg};在a.js端。如果它不应该在导出中使用{},则@Mark不应该在导出中使用{},除非您正在导出对象。如果这样做,那么导入也会更改。从“/GotMsg”导入{GotMsg};我现在明白了。谢谢,对不起。我想知道为什么我不能使用import*作为b.js中“scripts/a”的测试?你应该能够做到。像那样导出const GotMsg。我明白了,这样做会将a.js中导出为testOK的所有内容导入。非常感谢。
export function test1() {}
export function test2() {}
import { test1, test2 } from './path/to/file'; 
// a.js
const GotMsg = {
  test1(key) {
    console.warn(`It is Test1 + ${key}`);
  },
  test2(key) {
    console.warn(`It is Test2 + ${key}`);
  },
};
export default GotMsg;

// b.js
import GotMsg from './scripts/a';

const result = GotMsg.test1('AA');
console.log(result);
// a.js
export const GotMsg = {
  test1(key) {
    console.warn(`It is Test1 + ${key}`);
  },
  test2(key) {
    console.warn(`It is Test2 + ${key}`);
  },
};

// b.js
import { GotMsg } from './scripts/a';