iT邦幫忙

2021 iThome 鐵人賽

DAY 28
0
Modern Web

摸索 WebSocket,遠望 WebRTC系列 第 28

Day27:歪樓+卡文(全英文筆記 - I)

鐵人賽寫到現在,其實主題中的內容還有很多可以實作的部分,但一方面是不確定時間到期後,鐵人賽系列還能不能繼續發文,另一方面是很想要回頭去重新翻修前面的文章,讓整個系列進行彙整統合,避免現在這種零散感。

不過,因為團隊的成員已全部都放棄了,所以某種程度上自己也有點懶散,打算接下來幾篇可能用題外話的方式湊足篇數,先回頭思考前面的筆記如何重構修改。

既然都要隨意寫了,我打算來挑戰來看看,用全英文的方式來寫筆記,內容的部分就設定為,如何用 webpack 起一個專案,當然文法正確與否我就不管了,單純就以 google 翻譯後還能看懂來呈現。

Init Webpack Project

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

Setting

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.

webpack dev server

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.


上一篇
Day26:優化修正
下一篇
Day28:繼續歪樓(全英文筆記 - II)
系列文
摸索 WebSocket,遠望 WebRTC30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

1
juck30808
iT邦研究生 1 級 ‧ 2021-10-14 12:32:51

恭喜即將邁入完賽階段~

DoDoBird iT邦新手 5 級 ‧ 2021-10-14 15:48:51 檢舉

感謝鼓勵,不過希望之後自己不要懶癌發作,可以乖乖的把整個系列文重新翻修完成。
/images/emoticon/emoticon02.gif

我要留言

立即登入留言