웹팩 바벨 화살표함수가 ES5 일반 함수로 트랜스파일 안 될 때...

IT공부중·2021년 3월 14일
1

삽질

목록 보기
19/24

웹팩으로 IE를 지원 하기 위해서 babel을 사용하고 core-js도 설정을 해주었다. 그 설정은 다음과 같았다.

babel.config.js

module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        target: {
            chrome: '78',
        	ie: '11'	
        },
        corejs: 3,
        useBuiltIns: 'entry',
        modules: false,
        shippedProposals: true
      }
    ],
    '@babel/preset-react'
  ]
};

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = (env, argv) => ({
  mode: argv.mode,
  entry: {
    main: './src/index.jsx'
  },
  output: {
    path: path.resolve('./dist'),
    filename: '[name].js'
  },
  resolve: {
    extensions: ['.js', '.jsx']
  },
  devtool: 'eval-cheap-source-map',
  devServer: {
    contentBase: path.join(__dirname, 'dist'),
    port: 8080,
    hot: true,
    historyApiFallback: true
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_moduels/,
        loader: 'babel-loader'
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './public/index.html'
    }),
    new CleanWebpackPlugin()
  ]
});

다음과 같이 설정을 해뒀는데 build를 해도 계속 화살표 함수가 바뀌지 않는 것이었다. babel.config.js에 target을 ie 11 이상으로 뒀기 때문에 당연히 ES5 문법으로 변환돼야할 줄 알았는데 아니었다.

글들을 찾아보니 Webpack v5 부터 transfile을 기본적으로 es6로 한다는 것 같다. 그래서 target을 적어줘야한다고 한다.

webpack에 target 속성을 추가했다.

webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = (env, argv) => ({
	...
  	target: ['web', 'es5'],
  	...
});

그랬더니 화살표 함수가 일반함수로 변환 되는 것을 확인할 수 있었다.

참고자료

https://isolution.pro/ko/q/so77337112/webpack-babel-transpile-object-arrow-hamsuga-jagdonghaji-anhseubnida
https://medium.com/@JayKariesch/webpack-5-beta-babel-loader-why-do-i-still-have-arrow-functions-6a22980dcae4
(해당 글 댓글)

profile
3년차 프론트엔드 개발자 문건우입니다.

4개의 댓글

comment-user-thumbnail
2021년 7월 6일

감사합니다. 큰 도움이 되었습니다.
글은 짧지만 정말 큰 도움이 되었습니다.

1개의 답글
comment-user-thumbnail
2021년 8월 2일

감사합니다 진짜 이거때문에 환장 하는 지경이었는데 ㅠ.ㅠ

1개의 답글