ABOUT ME

Today
Yesterday
Total
  • webpack
    프로그래밍/Javascript 2021. 10. 25. 15:34

    1. 프로젝트를 생성한다, 추가적인 정보 입력 없이 생성하기 위해 옵션 -y 를 추가한다

    npm init -y

     

    2. webpack, webpack-cli, webpack-dev-server 패키지를 설치한다

    npm i -D webpack webpack-cli webpack-dev-server
    • webpack-cli 패키지: cli 를 지원해주는 패키지로, scripts 부분에 webpack 명령을 사용할 수 있게 해줌
    • webpack-dev-server 패키지: 개발서버를 오픈할 때 페이지 새로고침이 가능하게 해줌

     

    webpack dev 서버를 통해 개발서버를 오픈하려면 구성파일을 제공해야 한다

     

    3. root 경로에 새 파일 webpack.config.js 를 생성해, 기본적인 webpack 의 구성옵션들을 지정해 준다

    - webpack.config.js 는 브라우저가 아닌 node.js 환경에서 동작한다, node.js 환경에서 동작하므로 module.exports 키워드를 사용해 설정한 구성옵션 객체를 내보낸다

    // webpack.config.js
    module.exports = {
    };

    사용할 수 있는 옵션에는 entry option, output option 등이 있다

     

     

     Entry

    An entry point indicates which module webpack should use to begin building out its internal dependency graph. Webpack will figure out which other modules and libraries that entry point depends on (directly and indirectly). By default, its value is  ./src/index.js

    module.exports = {
        entry: './path/to/my/entry/file.js',
    };

    We can also pass an array of file paths to the entry property which creates what is known as a "multi-main entry". This is useful when you would like to inject multiple dependent files together and graph their dependencies into one "chunk"

    module.exports = {
        entry: ['./src/file_1.js', './src/file_2.js'],
    };

     

     

     Output

    The output property tells webpack where to emit the bundles it creates and how to name these files. It defaults to ./dist/main.js  for the main output file and to the  ./dist  folder for any other generated file. 

    - clean: true 옵션을 설정해주면, 새롭게 build 명령을 했을 때 이전 build 결과물을 지워주고 다시 결과물을 생성한다

    const path = require('path');
    
    module.exports = {
        output: {
        	path: path.resolve(__dirname, 'dist'),
            filename: 'my-first-webpack.bundle.js',
            clean: true, // Clean the output directory before emit
        }
    };

    there's more options in output.clean props, dry and keep.

    module.exports = {
        output: {
            clean: {
            	dry: true, // Log the assets that should be removed instead of deleting them
                keep: /ignored\/dir\//, // Keep these assets under 'ignored/dir'
            },
        }
    };

    - the output directory as an absolute path.

     

    - require 함수를 이용해서 node js 에서 제공하는 전역모듈인 path 모듈을 가져온다

    - __dirname 역시 node js 에서 사용 가능한 전역변수이며, 현재 파일이 위치한 바로 그 경로를 지칭한다

    - path 변수의 resolve 메소드는 1, 2번째 인수의 기본적 경로를 합쳐주는 역할을 한다

     

     

     Loaders

    Out of the box, webpack only understands JavaScript and JSON files. Loaders allow webpack to process other types of files and convert them into valid modules that can be consumed by your application and added to the dependency graph

     

    At a high level, loaders have two properties in your webpack cofiguration:

    1. The test property identifies which file or files should be transformed
    2. The use property indicates which loader should be used to do the transforming
    module.exports = {
        module: {
        	rules: [
              {
                test: /\.css$/,
                use: ["style-loader", "css-loader"], 
              },
            ],
        }
    };

    > "Hey webpack compiler, when you come accross a path that resolves to a '.css' file inside a  require() / import  statement, use the  "css-loader" and "style-loader"  to transform it before you add it to the bundle

     

     

    webpack 에 의해 번들된 결과물이 main.js 파일 뿐이기 때문에, 개발 서버를 띄울 때 화면이 보이지 않는다. index.html 을 삽입해 개발서버를 오픈할 수 있다. 

     

    4. 개발 의존성 모듈로 html-webpack-plugin 을 설치한다

    npm i -D html-webpack-plugin

     

     Plugins

      While loaders are used to transform certain types of modules, plugins can be leveraged to perform a wider range of tasks like bundle optimization, asset management and injection of environment variables

      In order to use a plugin, you need to require() it and add it to the plugins array. Most plugins are customizable through options. Since you can use a plugin multiple times in a configuration for different purposes, you need to create an instance of it by calling it with the new operator.

    const HtmlWebpackPlugin = require('html-webpack-plugin'); // installed via npm
    
    module.exports = {
    	plugins: [new HtmlWebpackPlugin({ template: './src/index.html' })],
    };

    In the example above, the html-webpack-plugin generates an HTML file for your application and automatically injects all your generated bundles into this file.

     

     

    5. static file 들을 사용하기 위해 새로운 패키지인 copy-webpack-plugin 을 설치한다

    npm i -D copy-webpack-plugin

    - 위 방법과 같이 new operator 를 사용해 create instance

     

     

    참고

    댓글