# Webpack ###### tags: `PID` Webpack俗稱打包 ## 使用流程(前置作業) 1. 建立一個資料夾 2. `npm init -y` 3. `npm i --save webpack webpack-cli` 此時的資料夾結構 >node_modules為npm檔案放置處 >package-lock.json不用管他 >package.json暫時不用管, 之後會在這裡增加webpack輸入 ``` |-node_modules |-package-lock.json |-package.json ``` 4. 增加兩個資料夾 src dist 此時的資料夾結構 >dist為打包後的輸出結果 >src需要打包的都放這, html不要放進來!!! ``` |-node_modules |-package-lock.json |-package.json |-dist |-src ``` 5. 在dist新增index.html, src新增index.js 此時的資料夾結構 >index.html是輸出結果, 可以按照正常流程打 >index.js是主要控制的js, 大部分的檔案都需要由這裡加入 ``` |-node_modules |-package-lock.json |-package.json |-dist |-index.html |-src |-index.js ``` 6. 更改package.json ```json= "description": "", "private": true, //新增它 "main": "index.js", //刪掉它 "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, ``` 7. `npm i --save-dev lodash` 8. 更改index.js ```javascript= import _ from 'lodash' function component() { const element = document.createElement('div'); element.innerHTML = _.join(['Hello', 'webpack'], ' '); return element; }; document.body.appendChild(component()); ``` 9. 更改index.html ```htmlmixed= <!doctype html> <html> <head></head> <body> <script src="bundle.js"></script> </body> </html> ``` 10. 新增檔案 webpack.config.js ```javascript= const path = require('path'); module.exports = { entry: './src/index.js', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist'), }, }; ``` 此時的資料夾結構 >webpack.config.js是控制webpack的程式, 之後要加入不同檔案的控制器也是在這 ``` |-node_modules |-package-lock.json |-package.json |-webpack.config.js |-dist |-index.html |-src |-index.js ``` 11. `npx webpack --config webpack.config.js` 此時的資料夾結構 >bundle.js是打包過後的產物 ``` |-node_modules |-package-lock.json |-package.json |-webpack.config.js |-dist |-index.html |-bundle.js |-src |-index.js ``` :::info 因為webpack和webpack-cli在下載時不是全域, 所以要用npx下指令 ::: 12. 更改package.json ```json= "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "webpack" //新增它 }, ``` 13. `npm run build` 這樣就會和`npx webpack --config webpack.config.js`一樣 ## 控制器下載 這邊只會有常用的, 剩下的自己去找 ### 先更改webpack.config.js ```javascript= module: { rules: [ // 東西放這裡 ], }, ``` ### CSS terminal `npm install --save-dev style-loader css-loader` webpack.config.js ```javascript= { test: /\.css$/, use: [ 'style-loader', 'css-loader', ], }, ``` index.js ```javascript= import './style.css' ```