-
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:
- The test property identifies which file or files should be transformed
- 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
참고
더보기https://webpack.js.org/concepts/
https://webpack.js.org/concepts/entry-points/
https://webpack.js.org/configuration/output/#outputclean
[React] CRA 없이 리액트 환경 만들기 - 배하람의 블로그
보통 리액트 관련 프로젝트는 CRA 툴을 사용하여 손쉽게 환경설정을 구축하는 것이 일반적이다. Webpack, Babel 등 설정하기가 귀찮은 많은 것들을 아주 편하게 해결해주는 좋은 툴이다. 하지만 단순
baeharam.netlify.app
.
'프로그래밍 > Javascript' 카테고리의 다른 글
Client CORS 문제 해결 (0) 2022.06.10 object.keys, values, entries, fromEntries / for...in loop (0) 2021.11.01 material-ui 사용기 createTheme, font, style, select (0) 2021.10.15 data 를 typescript enum 으로 매칭하기 (0) 2021.10.14 Array, Object 관련 메소드 (0) 2021.09.07