Mark
Mark

Reputation: 25

ES6 Using Export And Import Got An Error

I want to use the function in another JS file, so I do this:

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);

And run in Chrome, but I got an error in Chrome developer tool:

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

How sould I do to solve the error? Thanks.

Upvotes: -1

Views: 172

Answers (2)

codejockie
codejockie

Reputation: 10892

The reason for that error is because you are not importing it correctly and you also did not export default 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);

Or you can export it like this:

// 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';

Upvotes: 0

Baruch
Baruch

Reputation: 2428

You're not exporting GotMsg in a.js

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

Then in b.js

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

// do things.

Another way of exporting would be to export each individual function

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

Then

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

Upvotes: 1

Related Questions