webpack
    - 모듈 번들러 : 모듈을 합쳐줌
    - css , 그림파일등을 모두 js모듈로 로드 가능
    - NodeJS, ReatJS등의 SPA(Single Page App)을 위한 모듈 번들러
    - 코드 단계에서 webpack과 연동해야 효율적
    - entry 속성에서 지정한 파일에서 사용되어야 작업실행


https://github.com/webpack/webpack - 50,157
    - v4.38.0 , 2019/07

https://webpack.js.org/


//==========
* 설치
https://webpack.js.org/guides/installation/

npm install --save-dev webpack
npm install --save-dev webpack-cli
npm install --save-dev @webpack-cli/init

npx webpack --version

    - package.json 파일 수정
"scripts": {
"build": "webpack --config webpack.config.js"
}

//=======
* 설정
https://webpack.js.org/configuration/

npx webpack-cli init
    - webpack.config.js 파일 생성
    - paskage.json 파일 수정
    - 필요 패키지 설치


//========
< 플러그인 >
https://webpack.js.org/plugins/
https://github.com/webpack-contrib/awesome-webpack#webpack-plugins


* html-webpack-plugin : 번들 된 js파일을 포함하는 html 파일을 생성

* babel-loader : babel, ES6 -> ES5

* terser-webpack-plugin : js 압축

* webpack-obfuscator : js 소스 난독화


//==================
//유틸
copy-webpack-plugin : 파일 복사
clean-webpack-plugin : 빌드전에 output 폴더 삭제


//================
//환경 변수 설정
* EnvironmentPlugin
    - process.env = Nodejs의 시스템 환경변수(windows 운영체제의 경우 set 명령으로 확인)

new webpack.EnvironmentPlugin({
  NODE_ENV: 'development', // process.env.NODE_ENV 값이 설정되어 있지 않으면 설정
  DEBUG: false
});

//================================
//CSS

* css-loader 
    - js 파일에 @import and url() like import/require()  명령되어있는 css 파일을 자바스크립트 모듈로 만듬
    - css -> javascript 코드로 변환


* style-loader
    - css-loader에서 변환한 css파일을 DOM에 추가

    - style 태그로 만듬
    - style-loader는 서버 사이드 렌더링을 지원하지 안음

//=====
* mini-css-extract-plugin : CSS 를 추출해서 별도 파일로 저장
    - 설정 : moduel 과 plugins 두 속성 모두에 설정해야 한다.

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

...
module: {
        rules: [
            {
                test: /\.css$/,
                use: [ MiniCssExtractPlugin.loader, 'css-loader' ]
            },
        ]
...

plugins: [
        new MiniCssExtractPlugin({    filename: '[name].css',     }),


//========
* postcss-loader
npm i -D postcss-loader cssnano
npm install cssnano --save-dev


//============
< JS & CSS 압축 > 

* terser-webpack-plugin : JS 압축

* optimize-css-assets-webpack-plugin : CSS 압축 

const TerserJSPlugin = require('terser-webpack-plugin');// js 압축
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');//css 압축

const MiniCssExtractPlugin = require('mini-css-extract-plugin');//css를 js에서 분리
    // css파일로 저장해야 압축할수있다.

    - 설정 파일
optimization: {
        minimize: true, 
        minimizer: [
            new TerserJSPlugin({}), //js 압축
            new OptimizeCSSAssetsPlugin({}), //css 압축



//=================
* sass-loader : Sass -> CSS 



//===========================
* file-loader 
    - 파일을 모듈로 로드해서 사용할수 있게 해줌
    - 파일을 지정한 경로에 복사


* url-loader
    - 설정한 사이즈보다 작은 이미지나 폰트 파일을 인라인화(base64로 인코딩)




//=================
optimization 속성
    - 웹팩4에서

  CommonsChunkPlugin, ModuleConcatenationPlugin ,UglifyJsPlugin, NoEmitOnErrorsPlugin, NamedModules 등이 

     ----> optimization 속성으로 대치됨




//===================
// 참고
https://www.zerocho.com/category/Webpack/post/58aa916d745ca90018e5301d

설치
npm install --save-dev file-loader  url-loader



//===============================

// webpack.config.js 샘플 

...더보기

const devMode = process.env.NODE_ENV !== 'production';
//console.log(process.env, process.env.NODE_ENV);
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const Dotenv = require('dotenv-webpack');

const TerserJSPlugin = require('terser-webpack-plugin'); // js 압축
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
var JavaScriptObfuscator = require('webpack-obfuscator');
//CSS
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); //css를 js에서 분리
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin'); //css 압축

const conf = {
    src: './src1/',
    dist: './dist1/'
}

console.log(__dirname, path.resolve(__dirname, conf.dist))

module.exports = {
    mode: 'production', //'production',//'development', //process.env.NODE_ENV 값을 설정
    target: 'web', //'node'
    entry: {
        app_main: ['./src1/app1.js', ], //결과물은 app_main.js
        //adminApp: './src1/adminApp.js'
    },
    output: {
        filename: '[name].js', //'[name].[chunkhash].js',
        path: path.resolve(__dirname, conf.dist)
    },
    module: {
        rules: [{
                test: /.(js|jsx)$/,
                loader: 'babel-loader', //json-loader는 내장
                include: [path.resolve(__dirname, conf.src)],                
                exclude: ['/node_modules'],
                options: {
                    plugins: [ //babel 플러그인
                        'syntax-dynamic-import',
                    ],
                    presets: [ //babel 설정
                        [
                            '@babel/preset-env',
                            {
                                modules: false //모듈기능이 없는 브라우저를 대상으로 빌드할때 
                            }
                        ]
                    ]
                },
            },
            {
                test: /\.css$/,
                use: [MiniCssExtractPlugin.loader, 'css-loader']
            },
            {
                test: /\.(png|jpe?g|gif)$/,
                use: [{
                    loader: 'file-loader',
                    options: {
                        name: '[name].[ext]', //'[path][name].[ext]',
                    },
                }, ],
            },
            {
                test: /\.scss$/,
                use: [
                    "style-loader", // creates style nodes from JS strings
                    "css-loader", // translates CSS into CommonJS
                    "sass-loader" // compiles Sass to CSS, using Node Sass by default
                ]
            }
            /* {
                test: /\.js$/,
                include: [ path.resolve(__dirname, conf.dist), path.resolve(__dirname, conf.src) ],
                enforce: 'post',
                use: { loader: 'obfuscator-loader', options: {} }
            }, */
            /*{
                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,
                },
            } */
        ]
    },
    plugins: [
        new webpack.ProgressPlugin(), //빌드 과정 표시
        new HtmlWebpackPlugin(), //js 파일을 로드할 html 파일을 생성
        //new webpack.HotModuleReplacementPlugin(),//HMR
        new webpack.EnvironmentPlugin({
            NODE_ENV: 'production', // use 'development' unless process.env.NODE_ENV is defined
            DEBUG: false
        }),
        //new webpack.WatchIgnorePlugin([conf.src]), //파일 감시   
        //new CleanWebpackPlugin(['dist']), // 빌드전 파일 삭제        
        new MiniCssExtractPlugin({  filename: '[name].css', }),
        new JavaScriptObfuscator({   rotateUnicodeArray: true  }, ['excluded_bundle_name.js']),//난독화

    ],
    optimization: {
        minimize: true, //
        minimizer: [
            //new TerserJSPlugin({}), //js 압축
            new OptimizeCSSAssetsPlugin({}), //css 압축       
            
        ],
        splitChunks: {
            cacheGroups: {
                vendors: {
                    priority: -10,
                    test: /[\\/]node_modules[\\/]/
                }
            },

            chunks: 'async',
            minChunks: 1,
            minSize: 30000,
            name: true
        }
    },
    resolve: {
        modules: ['node_modules'],
        extensions: ['.js', '.json', '.jsx', '.css'],
//참조할 파일 확장자 순서, 
//import File from '../path/to/file'; 처럼 확장자를 생략할수 있게 한다.
    },
    watch: false, //변경 감시
    watchOptions: {
        aggregateTimeout: 1500,
        //ignored: ['files/**/*.js', 'node_modules']
    },
    devServer: { //웹서버
        open: false, //브라우저 열기
        hot: false, //HMR
        inline: true, //웹서버 콘솔에 빌드 메시지 보임
        contentBase: path.join(__dirname, conf.dist),
        compress: true,
        port: 9000,
    }
};

//

'Code > JavaScript' 카테고리의 다른 글

[Javascript] Grunt 사용법  (0) 2019.07.28
[Javascript] gulp 사용법  (0) 2019.07.28
[Javascript] webpack 사용법  (0) 2019.07.28
[Javascript] *.mjs 파일을 import 하려고 하면 에러 발생 , 해결 방법  (0) 2019.07.26
[Vue.js] Nuxt.js  (0) 2019.07.23
[Javascript] axios (ajax)  (0) 2019.07.22
Posted by 코덴스

댓글을 달아 주세요