普通文組 2.5

「webpack環境設置步驟」相關筆記

總結

使用 webpack(本次搭配 axios 與 vue)開發前端 web APP 時的環境相關設置筆記 2021/8/4 更新:追加 SCSS 相關設定

環境

webpack: 5.38.1
webpack-cli: 4.7.2
vue: 2.6.14
os: Windows_NT 10.0.18363 win32 x64

// 2021/8/4追加
node-sass: 6.0.1
sass-loader: 12.1.0

步驟

  1. 移動到專案資料夾內,在終端機輸入npm init -y
  • -y可跳過所有關於package.json的設定問題
  • npm-init: If the initializer is omitted (by just calling npm init), init will fall back to legacy init behavior. It will ask you a bunch of questions, and then write a package.json for you. You can also use -y/--yes to skip the questionnaire altogether.
  1. 安裝webpackwebpack-cliaxiosvuehtml-webpack-plugin
  • npm install <package name> --save-dev
  • What is the difference between —save and —save-dev?
  • npm: devDependencies: If someone is planning on downloading and using your module in their program, then they probably don’t want or need to download and build the external test or documentation framework that you use. In this case, it’s best to map these additional items in a devDependencies object.
  1. package.json設定如下:
  • webpack --watch: This means that after the initial build, webpack will continue to watch for changes in any of the resolved files. 執行npm run watch的話,webpack 會自動更新修改後的 src 內容;搭配 vs code liver server 的話,就能及時觀察到修正後的結果
  1. 在根目錄中建立webpack.config.js,(在專案需要使用 vue 的情況下)設定如下:
  1. 在根目錄中建立資料夾src,其中的檔案名稱需與webpack.config.js搭配,故使用index.jstemplate.html
  1. 在終端機執行npm run build後,根目錄中出現資料夾dist,內有index.htmlmain.js

並且main.js已經根據webpack.config.jsHtmlWebpackPlugin的設定,自動嵌入<body>底部 使用 webpack 進行打包的步驟到此結束

資料夾結構

folder structure

補充:若須導入.css

  1. 安裝css-loadermini-css-extract-pluginnpm i css-loader mini-css-extract-plugin -D
  2. index.js中匯入.css 檔案
import "./bootstrap.bundle";
import "./bootstrap.css";
import "./style.css";
  1. webpack.config.js加入以下內容:
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
  plugins: [new MiniCssExtractPlugin()],
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
    ],
  },
};
  • MiniCssExtractPlugin:此 plugin 會在執行npm run build時將(匯入 index.js 的).css 檔案獨立出來,並嵌入index.html中(預設在<head>尾端,可透過insert參數修改)
  • Webpack config: Module Rule.test: Include all modules that pass test assertion. If you supply a Rule.test option, you cannot also supply a Rule.resource.

補充:若須導入.scss

  1. 除上述提及之 package 之外,追加安裝node-sasssass-loader
  2. webpack.config.js的 plugins 與 module 設定如下:
plugins: [
  new MiniCssExtractPlugin(),
  new HtmlWebpackPlugin({
    inject: 'body',
    template: './src/index.html'
  })
],
module: {
  rules: [
    {
      test: /\.scss$/,
      use: [
        MiniCssExtractPlugin.loader,
        'css-loader',
        'sass-loader'
      ]
    }
  ]
}

參考文件