본문 바로가기

프로그래밍 공부내용/리액트(React)

절대경로로 import 하기

 

1. js를 이용해서

 

 

Importing a Component | Create React App

This project setup supports ES6 modules thanks to webpack.

create-react-app.dev

 

원문이다

 

 

jsconfig나 tsconfig 파일에 아래와 같은걸 추가하면

 

{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": ["src"]
}

 

baseUrl이 './src' 파일로 설정되고

 

src/components/Button.js에 잇는 Button을  import 한다고 했을 시

import Button from 'components/Button';

처럼 좀 더 간단하게 import 할 수 있다.

 

 

1. Ts를 이용해서

 

TSConfig Reference - Docs on every TSConfig option

From allowJs to useDefineForClassFields the TSConfig reference includes information about all of the active compiler flags setting up a TypeScript project.

www.typescriptlang.org

{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
        "app/*": ["app/*"],
        "config/*": ["app/_config/*"],
        "environment/*": ["environments/*"],
        "shared/*": ["app/_shared/*"],
        "helpers/*": ["helpers/*"],
        "tests/*": ["tests/*"]
    },
}

이렇게 할 수 있다.

 

 

 

3. 웹팩으로 해결하기

 

Resolve | webpack

webpack is a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset.

webpack.js.org

webpack.config.js에 상대경로를 등록할 수도 있다.

const path = require('path');

module.exports = {
  //...
  resolve: {
    alias: {
      Utilities: path.resolve(__dirname, 'src/utilities/'),
      Templates: path.resolve(__dirname, 'src/templates/'),
    },
  },
};

webpack.config.js에서 이렇게 해주면

 

 

import Utility from '../../utilities/utility';

 

이렇게 안쓰고

 

 

import Utility from 'Utilities/utility';

이렇게 쓸 수 있다.

 

 

 

 

 

로이정님과 록바크루가 알려준 꿀팁~