gpt4 book ai didi

javascript - ES6使用导出和导入出现错误

转载 作者:行者123 更新时间:2023-12-03 01:31:23 26 4
gpt4 key购买 nike

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

a.js

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

b.js

import * as test from 'scripts/a'
const result = test.GotMsg.test1('AA');
console.log(result);

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

Uncaught (in promise) TypeError: Cannot read property 'test1' of undefined at eval

我该如何解决该错误?谢谢。

最佳答案

您没有在 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() {}

然后

import { test1, test2 } from './path/to/file'; 

关于javascript - ES6使用导出和导入出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51280469/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com