Peiyun Lee
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    ###### tags: `前端技能樹` # 模組化開發好幫手 — 打包工具 Webpack ### 為什麼要使用 Webpack? 在前一篇文章提到,有愈來愈多開源套件,像是 React、Styled-components 等等,可以幫助我們加速開發。當功能愈來愈多,將所有程式碼都寫在同一個 JS 檔案中會難以管理。 如果能以模組化的方式進行開發,將程式碼拆開成不同的檔案,讓每個檔案各自串聯所使用到的程式碼或套件,不只可以加速網頁載入,也更可以提升專案的維護性。為了在瀏覽器上達成這樣的模組化開發,就有了 webpack 這樣的打包工具出現。 ## Webpack 如所說的:Webpack 是一個「打包工具」,將各種模組套件和資源打包成一個檔案,讓瀏覽器能夠正常編譯模組化的程式碼。它可以做到: - 打包多個 JS 檔案變成單一的檔案,解決使用多個 JS 檔造成變數污染的問題 - 能夠在程式碼中使用 ```import``` 引入 npm packages - 引入任何類型的檔案到 JS ,例如:圖片檔 - 優化程式碼 - ... ![](https://i.imgur.com/ueoOblR.png) 讓我們直接用一個範例來演示 webpack 是如何打包的,首先在 test.js ,有一個要在 index.js 使用的函式 ```test()```: test.js ```javascript= export default function test() { return "hello" } ``` index.js ```javascript= document.getElementById('target').innerText = test(); ``` 在 HTML 加入 Script,目前需要同時引入 test.js 才能在 index.js 使用 ```test()```: index.html ```javascript= <!DOCTYPE html> <html lang="en"> <head>...</head> <body> <div id="target"></div> <script src="./test.js"></script> <script src="./index.js"></script> </body> </html> ``` ### 安裝 webpack 透過 npm 安裝 webpack、webpack-cli: ```= npm init npm install webpack webpack-cli --save-dev ``` ### webpack.config.js 設定配置檔 webpack.config.js,告訴 webpack 該如何編譯和打包程式碼: ```webpack= module.exports = { mode: "development", entry: "./index.js", output: { path: __dirname, filename: "bundle.js", }, }; ``` - ```mode```:可以設定執行模式為 development 或 production。 - ```entry```:設定入口文件為 index.js - ```output```:輸出的相關設定 - ```path```:指定打包後輸出文件的目錄 - ```filname```:打包輸出的檔名 建立 webpack 的配置檔後,修改一下先前的範例,改成直接在 index.js 使用 ```import``` 引入 ```test()```。 index.js ```javascript= import test from './test.js' document.getElementById('target').innerText = test(); ``` ### 執行 webpack 在 package.json 的 scripts 屬性新增執行指令: ```json= "scripts": { "start": "webpack" }, ``` ![](https://i.imgur.com/7wd821c.png) 接著就可以輸入指令執行 webpack 打包檔案囉 ``` npm run start ``` ![](https://i.imgur.com/ezuwyl3.png) 依照上面視窗顯示的執行畫面,webpack 會將 index.js 和 test.js 一併打包成指定的檔案 bundle.js,這樣 HTML 就只要引入這一份程式碼,就可以有和之前分別引入兩份 script 相同的效果。 ![](https://i.imgur.com/HvAs4OP.png) index.html ```javascript= <!DOCTYPE html> <html lang="en"> <head>...</head> <body> <div id="target"></div> <script src="./bundle.js"></script> </body> </html> ``` ![](https://i.imgur.com/M9r1Ajk.png) ## Loader 在一開始有提到可以引入任何類型的檔案,例如:圖片檔、CSS等等, 而 webpack 會透過 Loader 將這些檔案進行預處理,才能成功加載這些文件。 舉例來說,要引入的是 CSS 檔,首先安裝會使用到 style-loader 和 css-loader。並且一樣設定配置檔,讓 webpack 知道該怎麼處理 CSS 類型的檔案: ``` npm install --save-dev style-loader css-loader ``` webpack.config.js ```javascript= ..., module: { rules: [ { test: /\.css$/, //結尾是.css的檔案 use: ["style-loader", "css-loader"] } ] } ``` 接下來新增 CSS 樣式,直接把檔案引入 JS: style.css ```css= body { background-color: #ffcccc; } ``` index.js ```javascript import './style.css'; ``` ![](https://i.imgur.com/t5KW1QC.png) >成功! ## 小結 希望到這邊大家都能了解使用 webpack 的理由,以及如何使用 webpack 進行模組化開發。下一篇文章,就會進入到 React 框架,我們會使用到一些套件,並且用模組化的方式進行開發,那就下章再見囉! 如果文章中有錯誤的地方,要麻煩各位大大不吝賜教;喜歡的話,也要記得幫我按讚訂閱喔❤️ ### 參考資料 - [webpack - document](https://webpack.js.org/concepts/) - [Webpack Tutorial 繁體中文 Gitbook](https://neighborhood999.github.io/webpack-tutorial-gitbook/) - [關於 Webpack,它是什麼?能夠做什麼?為什麼?怎麼做?— freeCodeCamp 的筆記](https://askie.today/what-is-webpack/) - [從模組化帶你認識 Webpack](https://5xruby.tw/posts/webpack)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully