Bỏ qua

a.js (entry module):

import { b } from "./b.js";

export const a = 2;

b.js:

import { a } from "./a.js";

console.log(a); // ReferenceError: Cannot access 'a' before initialization
export const b = 1;

Cách 1

function a_js() {
  var b = b_js(); // unnecessary line
  return 2;
}

function b_js() {
  var a = a_js();
  console.log(a);
  return 1;
}

Cách 2

a.js:

import { logA, b } from "./b.js";

export const a = 2;

logA();
console.log(b);

b.js:

import { a } from "./a.js";

export const b = 1;

export function logA() {
  console.log(a);
}

Nguồn:: Does importing a module mean embedding the code of the module at the line of the import statement?

Việc chia các lệnh trong kịch bản thành các hàm nhỏ hơn sẽ giúp dễ bắt lỗi hơn
Khi import một hàm thì cả file chứa hàm đó sẽ được chạy. Các import cũng sẽ chạy theo, dù là để import vào một hàm khác mình không import


Cập nhật lần cuối : 30 tháng 6, 2024
Tạo : 12 tháng 10, 2023