본문 바로가기

패스트캠퍼스 챌린지 < 프론트엔드-react>

[패스트캠퍼스 수강후기] 프론트엔드 강의 49회차 미션

오늘은 39. webpack 에서 프로덕션 모드와 파일로더까지 24번째 클립까지 들었다

ㅠㅠ알아듣기 어려워서 오래 걸린다...

 

프로덕션모드설정

<webpack.common.js> 추가 생성

const path = require('path');

const HtmlWebpackPlugin = require('html-webpack-plugin');

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

const MiniCssExtractPlugin = require('mini-css-extract-plugin'); 

 

module.exports = {

    entry: './index.js',

    output: {

        filename: '[name].[chunkhash].js',

        path: path.resolve(__dirname'dist')

    }, 

    module: {

        rules: [

            {

                test:/\.css$/i,

                use:[

                    {

                        loader: MiniCSSExtractPlugin.loader   

                    },

                    {

                        loader: 'css-loader',

                        options: {

                            modules: true

                        }  

                    }                     

                ] 

            }, {

                text: /\.hbs$/,

                use: ['handlebars-loader']

            }

        ]

    }, 

           

plugins: [

    new MiniCssExtractPlugin ({

        filename: '[contenthash].css'

    }),

    new HtmlWebpackPlugin ({

     title: 'webpack',

     template: './template.hbs',

     meta: {

         viewport: 'width=device-width, initial-sacle=1.0'

     },

    minify : {

        collapseWhitespace: true,

        useShortDoctype: true,

        removeScriptTypeAttributes: true

    }

     }),

     new CleanWebpackPlugin() 

   ]

}   

<webpack.dev.js> 추가 생성

const mrege = require('webpack-merge');

const common = require('./webpack.common');

 

const config = {

    mode: 'development'

};

 

module.exports = merge(commonconfig)

<webpack.prod.js> 추가 생성

const path = require('webpack=merge');

const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');

const TerserwebPlugin = require('terser-webpack-plugin');

const common = require ('/webpack.common')

 

const config = {

    plugins : [

        new OptimizeCssAssetsPlugin({

            assetNameRegExp: /\.css$/g,

            cssProcessor: require('cssnano'),

            cssProcessorPluginOptions: {

              preset: ['default', { discardComments: { removeAll: true }}],

           },

            canPrint: true

        })

    ],

    optimization : {

        runtimeChunk {

            name: 'runtime'

        },

        splitChunks: {

            cacheGroups: {

                commons: {

                    test: /[\\/]node_modules[\\/]/,

                    name: 'venders',

                    chunks: 'all'

                }

            }

        },

        minimize: true,

        minimizer: [new TerserWebpackPlugin({

            cache: true

        })]    

    },

    mode'production'    

};

 

module.exports = merge(commonconfig)

 

그리고  <package.json>에서 script에 입력 후 실행

"dev": "webpack --config webpack.dev.js",

"build": "webpack --config webpack.prod.js"

 

디파인플러그인

빌드를 진행할 때상속값을 만들어서 모듈들이 상속값을 어디서도 사용할 수 있게 해줌

모듈 내부에 있어서 따로 npm으로 설치할 필요는 없음

<webpack.common.js> 수정

const path = require('path');

const HtmlWebpackPlugin = require('html-webpack-plugin');

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

const MiniCssExtractPlugin = require('mini-css-extract-plugin'); 

const webpack = require('webpack'); 

 

module.exports = {

    entry: './index.js',

    output: {

        filename: '[name].[chunkhash].js',

        path: path.resolve(__dirname'dist')

    }, 

    module: {

        rules: [

            {

                test:/\.css$/i,

                use:[

                    {

                        loader: MiniCSSExtractPlugin.loader   

                    },

                    {

                        loader: 'css-loader',

                        options: {

                            modules: true

                        }  

                    }                     

                ] 

            }, {

                text: /\.hbs$/,

                use: ['handlebars-loader']

            }

        ]

    }, 

           

plugins: [

    new MiniCssExtractPlugin ({

        filename: '[contenthash].css'

    }),

    new HtmlWebpackPlugin ({

     title: 'webpack',

     template: './template.hbs',

     meta: {

         viewport: 'width=device-width, initial-sacle=1.0'

     },

    minify : {

        collapseWhitespace: true,

        useShortDoctype: true,

        removeScriptTypeAttributes: true

    }

     }),

     new CleanWebpackPlugin(),

     new webpack.DefinePlugin({ 

        IS_PRODUCTION: true

     }),

   ]

}   

<index.js>도 수정

import 'normalize.css'

import styles from './index.css'

import $ from 'jquery';

 

function component () {

    const element = document.createElement('div');

    element.innerHTML = "Hello webpack";

 

    console.log(styles);

 

    element.classList = style.helloWebpack;

 

    return element;

}

 

document.body.appendChild(component());

console.log($(`.${styles.helloWebpack}`).length);

console.log(`IS_PRODUCTION MODE: ${IS_PRODUCTION}`);

 

<package.json> script 수정

"dev": "NODE_ENV=DEVELOPMENT webpack --config webpack.dev.js",

"build": "NODE_ENV=PRODUCTION webpack --config webpack.prod.js"

 

결과가dev일때는 압축이 되지않고 production 일땐 압축이 되게 하려면

<common.js>

const isProduction = process.env.NODE_ENV === 'PRODUCTION' ;

추가

minify : isProduction ? {

        collapseWhitespace: true,

        useShortDoctype: true,

        removeScriptTypeAttributes: true

    } : false

수정

 

데브서브 설정

<common.js> 바꾸고

new webpack.DefinePlugin({ 

        IS_PRODUCTION: isProduction

npm i -D webpack-dev-server 

./node_modules/.bin/webpack-dev-server 만 쓰면 에러가 뜸

./node_modules/.bin/webpack-dev-server --config webpack.dev.js 해야 실행되는데 매번 쓰기 귀찮으므로

다시<package.json>scripts에서

 "start" : "NODE_ENV=DEVELOPMENT webpack-dev-server --config webpack.dev.js",

그리고 npm start 쓰면 작동됨

이후 css에서 색을 바꾸면, 다시 빌드가 실행됨

 

historyApiFallback

<webpack.dev.js> 수정

const mrege = require('webpack-merge');

const common = require('./webpack.common');

 

const config = {

    mode: 'development'

    devServer: {

        historyApiFalback: false

    }

};

 

module.exports = merge(commonconfig)

 

historyApiFalback : 라우팅과 관련된 키 특정 라우팅으로 지정했을 때 따로 이동할 수 있도록 지정

 false vs true vs 객체값 rewrites (특정값으로 갈 수 있게 지정가능) from 과 to로

(예)

 historyApiFalback {

             rewrites: [

                 { from: /^\subpage$/to: 'subpage.html'},

                 { from: /./, to: '404.html' } //특정경우가 아닌 경우에는 다 404페이지로

             ]

        } 

(예)

devServer: {

        open: true//새 탭이 열리면서 실행

        overlay: true// 에러메세지 자체가 화면에 뜸

        historyApiFalback {

             rewrites: [

                 { from: /^\subpage$/to: 'subpage.html'},

             ]

        },

     port: 3333 //local host:3333 검색하면 나옴

 

이미지파일도 모듈로 다루기

 

<index.js> 수정

import 'normalize.css'

import styles from './index.css'

import $ from 'jquery';

import slackImg from './assets/slack.jpg';

 

function component () {

    const element = document.createElement('div');

    element.innerHTML = "Hello webpack";

 

    const imgElement = document.createElement('img');

    imgElement.src = slackImg;//

 

    console.log(slackImg); //

    console.log(styles);

    element.appendChild(imgElement);

 

    element.classList = style.helloWebpack;

 

    return element;

}

 

document.body.appendChild(component());

console.log($(`.${styles.helloWebpack}`).length);

console.log(`IS_PRODUCTION MODE: ${IS_PRODUCTION}`);

 

<common.js> 수정

const path = require('path');

const HtmlWebpackPlugin = require('html-webpack-plugin');

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

const MiniCssExtractPlugin = require('mini-css-extract-plugin'); 

const webpack = require('webpack'); 

const isProduction = process.env.NODE_ENV === 'PRODUCTION' ;

 

module.exports = {

    entry: './index.js',

    output: {

        filename: '[name].[chunkhash].js',

        path: path.resolve(__dirname'dist')

    }, 

    module: {

        rules: [

            {

                test:/\.css$/i,

                use:[

                    {

                        loader: MiniCSSExtractPlugin.loader   

                    },

                    {

                        loader: 'css-loader',

                        options: {

                            modules: true

                        }  

                    }                     

                ] 

            }, {

                test: /\.hbs$/,

                use: ['handlebars-loader']

            }, {

                test: /\.(png|jpe?g|gif)$/i,

                use: [{

                    loader: 'file-loader',

                    options: {

                        name: '[contenthash].[ext]',

                        publicPath: 'assets/',

                        outputPath: 'assets/'

                    }

                }]

            }

        ]

    }, 

           

plugins: [

    new MiniCssExtractPlugin ({

        filename: '[contenthash].css'

    }),

    new HtmlWebpackPlugin ({

     title: 'webpack',

     template: './template.hbs',

     meta: {

         viewport: 'width=device-width, initial-sacle=1.0'

     },

    minify : isProduction ? {

        collapseWhitespace: true,

        useShortDoctype: true,

        removeScriptTypeAttributes: true

    } : false

     }),

     new CleanWebpackPlugin(),

     new webpack.DefinePlugin({ 

        IS_PRODUCTION: isProduction

     }),

   ]

}   

 

파일로더 설정 개선

src안에 index.css, index.js, assets안에 이미지

 entry: './src/index.js'

<common.js> 수정

                    options: {

                        name() {

                            if(!isProduction) {

                                return '[path][name].[ext]';

                            }

                            return '[contenthash][ext]';

                        },

                        publicPath: 'assets/',

                        outputPath: 'assets/'

                    }

 

진짜 초반부 강사님들처럼 브이에스 스튜디오 코드 따라가는 거 말고

강좌내용에 대한 판서나 피피티 좀 있었으면 좋겠다...

뭐라고 말하시는지 너무 안들리고 정리하기가 힘들다 ㅜㅠ

 

https://bit.ly/3g7RJpi

 

프론트엔드 개발 올인원 패키지 with React Online. | 패스트캠퍼스

프론트엔드 개발 러닝패스, 이 강의 패키지 하나로 끝낸다!

www.fastcampus.co.kr