Dandy Now!
  • [JavaScript] ESModule 사용시 발생하는 net::err_aborted 404 (not found) 에러
    2024년 04월 14일 21시 33분 06초에 업로드 된 글입니다.
    작성자: DandyNow
    728x90
    반응형

    1. ESModule 사용 후 발생한 net::err_aborted 404 (not found) 에러

    타입 스크립트를 사용한 프로젝트에서 ESModule을 사용해 불러오기를 하였는데 [그림 1]과 같은 에러가 발생했다.

    [그림 1] net::err_aborted 404 (not found) 에러

     

    2. 모듈의 확장자까지 작성해야 한다!

    아래의 코드와 같이 app.ts 파일에 new 키워드로 클래스의 인스턴스를 생성했다. 

    new ProjectInput();

    app.ts에는 ProjectInput 클래스가 없으며 components 폴더 내 project-input.ts 파일에 클래스가 존재한다. 따라서 아래와 같이 해당 모듈을 임폴트했다. 이때 직접 작성하지는 않았고 VSCode의 "ctrl + space" 단축키를 이용해 자동 완성하였다.

    import { ProjectInput } from "./components/project-input";

    이 상태에서 프로젝트를 실행한 후 만난 에러가  "net::err_aborted 404 (not found)"이다. 구글링 결과 이 문제는 간단하게 해결될 수 있었는데 아래 코드와 같이 모듈의 확장자를 붙여주면 된다.

    import { ProjectInput } from "./components/project-input.js";

    😉 타입 스크립트라서 .ts를 붙여야 할 것 같지만 결국 실행은 컴파일된 자바스크립트 파일이 실행되기 때문에 .js를 붙이면 된다.

    리액트에서는 모듈 임폴트시 확장자를 붙일 필요가 없지만 자바스크립트에서는 반드시 붙여야 한다!


    ※ 모듈 임폴트 방법들

    // ./modules/square.js
    
    export const name = "square";
    
    export function draw(ctx, length, x, y, color) {
      ctx.fillStyle = color;
      ctx.fillRect(x, y, length, length);
    
      return { length, x, y, color };
    }

    위와 같은 변수(name), 함수(draw)가 작성된 모듈을 임폴트할 때 아래와 같이 다양한 방식을 이용할 수 있다.

     

    1. 구조분해 할당

    import { name, draw } from "./modules/square.js";

     

    2. 구조분해 할당 + 별칭

    import { name as squareName, draw } from "./shapes/square.js";

    name에 squareName이라는 별칭을 주었기 때문에 squareName을 이용해야 한다.

     

    3. 그룹화(module object)

    import * as Square from "./shapes/square.js";

    Square로 그룹화 되었고 Square.name, Square.draw와 같은 방식으로 사용해야 한다.

     

    4. default exports의 경우

    // ./shapes/square.js
    
    // default 키워드는 모듈에 하나만 존재할 수 있다.
    export default function draw(ctx, length, x, y, color) {
      ctx.fillStyle = color;
      ctx.fillRect(x, y, length, length);
    
      return { length, x, y, color };
    }

    위 코드 처럼 기본 내보내기 방식으로 정의된 draw 함수의 경우에는 아래와 같이 함수명을 임의로 지정(draw를 SquareDraw로 불러옴)하여 불러올 수 있다.

    import SquareDraw from "./shapes/square.js";

     

    ✔️ 참고 자료 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules

    728x90
    반응형
    댓글