我想在另一个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开发人员工具中出现错误:
未捕获(承诺)TypeError:无法读取的属性“ test1” 未定义 在评估时
我该如何解决该错误? 谢谢。
答案 0 :(得分:1)
您不是要在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';
答案 1 :(得分:0)
该错误的原因是因为您没有正确导入它,也没有导出默认的GotMsg
。
// 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';