[JS] 선언한 모듈로 이동하기 (alias) - Go to declaration

[JS] 선언한 모듈로 이동하기 (alias) - Go to declaration

이채현

문제

많은 사람들은 선언한 모듈들을 command/ctrl + click으로 해당 파일로 바로 이동하거나 자동완성이 되게하는 IDE나 Editor의 기능을 사용할 것이다. 그리고 babel-plugin-module-resolver을 통해 모듈의 경로를 별칭으로 바꿔서 사용할 것이다. 하지만 별칭으로 바꾸면서 위 기능이 깨지는 문제가 종종 있다. 그리고 이 문제는 플러그인쪽에서는 해결되지 않고 있다. npm에 올라온 최신버전은 이미 2년이 지났다.

babel-plugin-module-resolver

해결

우리는 jsconfig.json을 사용하여 IDE가 사용자 지정 resolve규칙을 따르도록 하는 것이 좋다. 이 접근 방식은 WebstormVS Code 모두 작동한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"#api/*": [
"./src/api/*"
],
"#assets/*": [
"./src/assets/*"
],
"#common/*": [
"./src/common/*"
],
"#component/*": [
"./src/component/*"
],
"#constant/*": [
"./src/constant/*"
],
"#container/*": [
"./src/container/*"
]
}
}
}
[JS] babelrc와 webpack.config

[JS] babelrc와 webpack.config

이채현

Webpack으로 React 프로젝트를 초기 설정하다가 ,

1
2
3
4
5
6
7
8
9
10
11
12
presets: [
[
'@babel/preset-env',
{
targets: {
browsers: ['> 5% in KR', 'last 2 chrome versions'],
},
debug: true,
},
],
'@babel/preset-react',
],

위 코드의 presets가 과연 .babelrc에 있어야 하는지, webpack.config.js에 있어야하는지 잘 모르겠어서 각 파일의 목적을 정리해보았다.

babelrc

.babelrcbabel의 설정을 위해 사용한다.

1
2
3
4
{
"presets": [...],
"plugins": [...]
}

webpack.config

물론 webpack.config.jswebpack의 설정을 위해 사용한다. 프로젝트 파일의 번들링과 관련된 설정들을 작성해준다. 그리고 babel과 관련된 설정들을 .babelrc가 아닌 webpack.config.js에서 babel-loader를 설정한 부분에 작성해줄 수도 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
...

module.exports = {

...

module: {
rules: [
{
test: /\\.js?/,
loader: 'babel-loader',
options: {
presets: [
[
'@babel/preset-env',
{
targets: {
browsers: ['> 5% in KR', 'last 2 chrome versions'],
},
debug:true,
},
],
'@babel/preset-react',
],
plugins: [
'@babel/plugin-proposal-class-properties',
'react-refresh/babel',
[
'module-resolver',
{
root: ['./src'],
alias: {
'#api': './src/api/',
'#assets': './src/asset/',
'#common': './src/common/',
'#component': './src/component/',
'#constant': './src/constant/',
'#container': './src/container/',
},
},
],
],
exclude: /node_modules/,
},
},
],
},

...

}

결론

결론은, babelpresetswebpack.config.js.babelrc 파일 둘 중 한 곳에만 있으면 된다! 그러나 babel cli를 이용하여 직접 코드 변환을 수행하거나 babel test 등을 돌릴 때에는 webpack을 거치지 않기 때문에 .babelrc에 작성하는 방식이 권장된다.

나는 webpack.config.js 내에 적어서 사용한다.