본문 바로가기
웹 프론트엔드/웹개발 용어 및 개념 정리

Webpack : Webpack 빌드후 자동으로 S3로 배포하기 (webpack-s3-plugin)

by 번데기 개발자 2022. 7. 22.
반응형

 

Webpack으로 웹 애플리케이션을 빌드한 뒤에 S3로 업로드를 해야 하는 경우가 있습니다.

 

보통 S3를 통한 정적 웹페이지 배포를 할 때, 또는 특정한 버킷 위에 Webpack으로 bundling 한 js파일을 업로드해야 할 경우가 있을 때 이러한 경우가 발생하게 됩니다.

 

수동으로 dist폴더 안에 있는 파일들을 drag-end-drop을 통해 S3로 업로드 할 수도 있지만, Webpack 명령어 사용 후에 자동으로 S3 Bucket에 올려주는 플러그인이 있어 한번 소개해드리도록 하겠습니다.

 

 

webpack-s3-plugin


오늘 설명해드릴 플러그인은 바로 webpack-s3-plugin 인데요, 아래 링크를 누르시면 npm 설명 페이지를 확인하실 수 있습니다.

 

 

webpack-s3-plugin

Uploads compiled assets to s3 after build. Latest version: 1.2.0-rc.0, last published: 2 years ago. Start using webpack-s3-plugin in your project by running `npm i webpack-s3-plugin`. There are 47 other projects in the npm registry using webpack-s3-plugin.

www.npmjs.com

 

해당 플러그인을 통해 Webpack으로 빌드 후 자동으로 S3로 업로드하는 Webpack 구성을 할 수 있습니다.

 

 

 

webpack-s3-plugin 사용법


const S3Plugin = require('webpack-s3-plugin');

new S3Plugin({
  s3Options: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
    region: 'us-west-1'
  },
  s3UploadOptions: {
    Bucket: 'MyBucket'
  },
})

 

사용법은 상당히 간단합니다.

 

webpack config 파일의 마지막 plugins부분에 다음과 같이 S3Plugin을 추가해주면 됩니다.

 

간단하게 옵션을 알아보겠습니다.

 

S3Options

  • accessKeyId : IAM credential 중에 access key
  • secretAccessKey: IAM credential 중에 access key
  • region: Bucket이 올라가 있는 region

 

S3UploadOptions

  • Bucket: S3의 Bucket 이름

 

new S3Plugin({
    // Exclude uploading of html
    exclude: /.*\.html$/,
    ...
})

 

exclude

  • Webpack으로 빌드된 파일들을 S3로 업로드할 때 업로드하지 않을 파일에 대해 정규식으로 표현
  • 정규식으로 필터링되지 않은 파일들은 모두 S3로 업로드
  • 정규식으로 필터링되면 필터링되면 S3로 업로드하지 않음

 

new S3Plugin({
	// Only upload css and js
	include: /.*\.(css|js)/,
}

 

include

  • Webpack으로 빌드된 파일들을 S3로 업로드할 파일에 대해 정규식으로 표현
  • 정규식으로 필터링된 파일만 S3로 업로드 
  • 정규식으로 필터링되지 않으면 S3로 업로드하지 않음

 

 

 

사용 예제


entry, loader, output, plugin 등의 개념에 대해 잘 모르시면 아래 링크를 참고해주세요. 

 

웹팩 이해하기 - 2

지난 글에서는 프론트엔드 개발 환경 설정을 위해 가장 많이 사용되는 웹팩의 정의와 필요성에 대해 알아보았다. (*웹팩 이해하기 -…

tecoble.techcourse.co.kr

// webpack.config.js

const S3Plugin = require('webpack-s3-plugin')

module.exports = {
    // 번들링을 시작하기 위한 최초 진입점으로 ./src/index.js 설정
    entry: {
        app: ['./src/index.js'],
    }, 

    // Js를 제외한 파일들을 번들링하기 위한 Loader 등록
    module: {
        rules: [
           {
            test: /\.s?css$/,
            use: [
                // Creates `style` nodes from JS strings
                'style-loader',
                // Translates CSS into CommonJS
                'css-loader',
                // Compiles Sass to CSS
                'sass-loader',
            ],
            },
            {
                type: 'javascript/auto',
                test: /\.(glb|png|svg|jpe?g|gif|hdr|json|mp3|mov|woff|woff2|eot|ttf|otf|mp4|webm|ico)$/,
                loader: 'file-loader',
                options: {
                    // name: 'static/media/[name].[hash:8].[ext]',
                    // name: '[name].[ext]',
                    outputPath: 'assets/',
                },
            },
        ],
        ...
        ...
    },

    // bundle의 최종 결과물 경로 빛 bunble 파일 이름 설정
    output: {
        path: path.join(__dirname, 'dist'),
        filename: 'bundle.js',
    },

    // Loader가 할수 없는 다른 작업들을 Plugin으로 수행
    // S3Plugin: webpack의 결과를 S3로 업로드하는 역활 수행
    plugins: [
        new S3Plugin({
            s3Options: {
                accessKeyId: AWS_ACCESS_KEY_ID,
                secretAccessKey: AWS_SECRET_ACCESS_KEY,
            },
            s3UploadOptions: {
                Bucket: 'MY_BUCKET_NAME',
            },
        }),
    ]
}

 

위 코드는 webpack 설정 파일의 예제입니다.

 

webpack 명령을 사용하면 webpack-s3-plugin을 이용하여 Webpack 빌드 후 S3로 업로드되는 것을 확인하실 수 있습니다.

 

 

 

 

마무리


오늘은 간단하게 Webpack 빌드 후 S3로 업로드까지 자동으로 해주는 플러그인에 대해 포스팅하였습니다.

 

다음에도 좋은 Webpack 플러그인이 있으면 공유드릴 예정입니다.

 

감사합니다.

반응형