初始化
npm init -y
安裝依賴
npm i webpack webpack-cli html-webpack-plugin -D
package.json
{ "name": "webpack-test", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "webpack-dev-server --open" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "html-webpack-plugin": "^3.2.0", "webpack": "^4.41.2", "webpack-cli": "^3.3.9", "webpack-dev-server": "^3.9.0" } }
webpack.config.js
const path = require('path') //導入htm-webpack-plugin插件 const htmlWebpackPlugin = require('html-webpack-plugin'); //這個配置文件初始就是一個js文件,通過node中的模塊操作 module.exports = { //入口,表示要使用webpack打包哪個文件 entry: path.join(__dirname, './src/main.js'), output: {//輸出文件相關的配置 path: path.join(__dirname, './dist'),//指定打包的文件輸出到哪個目錄 filename: 'bundle.js'//指定輸出的文件名稱 }, devServer: {//配置dev-server命令參數的配置項 port: 3000,//設置啟動的端口號 contentBase: 'src',//設置默認目錄 hot: true//啟動熱更新 }, plugins: [//插件數組 new htmlWebpackPlugin({ //創建一個在內存中生成html頁面插件的配置對象 template:path.join(__dirname,'./src/index.html'), //指定模版頁面生成內存中的hmtl filename:'index.html' //指定生成的頁面名稱 }) ] }