鐵人賽寫到現在,其實主題中的內容還有很多可以實作的部分,但一方面是不確定時間到期後,鐵人賽系列還能不能繼續發文,另一方面是很想要回頭去重新翻修前面的文章,讓整個系列進行彙整統合,避免現在這種零散感。
不過,因為團隊的成員已全部都放棄了,所以某種程度上自己也有點懶散,打算接下來幾篇可能用題外話的方式湊足篇數,先回頭思考前面的筆記如何重構修改。
既然都要隨意寫了,我打算來挑戰來看看,用全英文的方式來寫筆記,內容的部分就設定為,如何用 webpack 起一個專案,當然文法正確與否我就不管了,單純就以 google 翻譯後還能看懂來呈現。
Require Node.js environment, I use node version v16.4.2, npm version v7.18.1.
Build package.json
mkdir project-name
cd project-name
npm init -y
Install webpack & webpack-cli in devDependencies, there not install global, avoid polluting other project webpack version.
npm install webpack webpack-cli -D
mkdir src
touch src/index.js webpack.config.js
Now you can see the structure as follows.
┣ ?src
┃ ┗ ?index.js
┣ ?.gitignore
┣ ?package.json
┗ ?webpack.config.js
Use node.js path api to generate dist in output bundle and setting entry file.
// webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.join(__dirname, 'dist'),
filename: 'main.bundle.js',
},
};
Writting something.
// src/index.js
console.log('test webpack');
Setting scripts.
// package.json
{
"scripts": {
"build": "webpack"
},
}
ok, you cna run npm run build, and you will see the dist folder is auto generated. And include main.bundle.js.
When we development, need server to running in browser, so we install webpack-dev-server plugin.
npm install webpack-dev-server -D
touch index.html in dist folder.
And content is follows as:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=\, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script src="./main.bundle.js"></script>
</body>
</html>
In webpack.config.js, you can pass through the devServer setting parameter.
module.exports = {
mode: 'development',
// ...
devServer: {
static: path.join(__dirname, 'dist'), // root
open: true, // auto open browsers
compress: true,
port: 3002,
},
};
Of the above, when npm run dev, your project can auto caught dist folder, open in browser port 3002. Because default have hotreload effect, so you don't need to manually setting.
恭喜即將邁入完賽階段~
感謝鼓勵,不過希望之後自己不要懶癌發作,可以乖乖的把整個系列文重新翻修完成。![]()