安裝nvm/node.js

新增一個webpack.config.js檔案

// webpack.confing.js
const path = require('path');

module.exports = {
	// entry 進入點
  entry: './src/index.js',
	// output 輸出編譯後
  output: {
		// node語法處理路徑轉換
    path: path.resolve(__dirname, 'dist'),
		// 編譯後的檔案名
    filename: 'index.bundle.js'
  }
};

設定webpack檔案

// 初始化packjson檔案
npm init -y

// 安裝webpack
npm install webpack webpack-cli --save-dev

新增啟動指令webpack (壓縮的production版本)

// package.json
{
  "name": "webpack-demo",
  "version": "1.0.0",
  "description": "",
  "main": "webpack.config.js",
  "scripts": {
    "webpack": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^5.11.1",
    "webpack-cli": "^4.3.1"
  }
}

啟動webpack

// commit line
npm run webpack

babel-loader掛載babel處理ES6+

https://github.com/babel/babel-loader

安裝

// commit line
npm install -D babel-loader @babel/core @babel/preset-env webpack

添加至webpack檔案中

// webpack.config.js
// module模塊中放的是須轉換的(js,sass...)
module: {
  rules: [
    {
      test: /\\.m?js$/,
      exclude: /node_modules/,
      use: {
        loader: 'babel-loader',
        options: {
          presets: [
            ['@babel/preset-env', { targets: "defaults" }]
          ]
        }
      }
    }
  ]
}

也可以新增.babelrc檔案設定presets