webpack-merge 설정

Taek·2020년 6월 14일
2
post-custom-banner

alias 경로를 추가할 때 dev, prod 각각 작성하는 것이 헷갈릴 때도 있고 비효율적이라는 생각이 들어 공통된 설정 값을 분리 했다.


  • 의존성 모듈 추가 (webpack plugin)
npm install --save-dev webpack-merge

  • webpack.config.js
// webpack.config.js
module.exports = function (env) {
    return require(`./webpack.${env}.js`);
};
// webpack.config.js
module.exports = function (env) {
    return require(`./webpack/${env.WEBPACK_SERVE ? 'dev' : 'prod'}.js`);
};

  • 공통 설정 분리
// webpack.common.js
const path = require("path");
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: ['@babel/polyfill', './src/index.js'],

    module: {
        rules: [
            {
                test: /\.(ts|tsx)$/,
                use: ['babel-loader', 'ts-loader'],
            },
            {
                test: /\.(js|jsx)$/,
                use: ['babel-loader'],
            },
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader'],
            },
            {
                test: /\.(ico|png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: 'url-loader',
                options: {
                    name: '[hash].[ext]',
                    limit: 10000,
                },
            },
        ],
    },

    resolve: {
        extensions: ['.js', '.jsx', '.ts', '.tsx'],
        alias: {
            '@': path.resolve(__dirname, "src/"),
        }
    },

    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: 'public/index.html',
        }),
    ],

    devtool: 'cheap-eval-source-map',
}

  • development webpack 환경 설정
// webpack.dev.js
const path = require("path");
const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');
const Dotenv = require("dotenv-webpack");

module.exports = merge(common, {
    mode: 'development',

    devServer: {
        historyApiFallback: true,
        inline: true,
        port: 3000,
        hot: true,
        publicPath: '/',
    },

    plugins: [
        new Dotenv({
            path: path.resolve(__dirname, "./.env.development"),
        }),
    ],
});

  • production webpack 환경 설정
// webpack.prod.js
const path = require("path");
const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');
const Dotenv = require("dotenv-webpack");

module.exports = merge(common, {
    mode: 'production',

    output: {
        filename: "bundle.js",
        path: path.resolve(__dirname, "dist"),
        publicPath: './',
    },

    plugins: [
        new Dotenv({
            path: path.resolve(__dirname, "./.env.production"),
        }),
    ],
});

자바스크립트 라이브러리 배포를 위한 웹팩(webpack) 설정 경험기

post-custom-banner

0개의 댓글