一、HtmlWebpackPlugin 自動生成基本的 html 頁面
二、開啓文件監聽
三、webpack-dev-server熱更新css
安裝依賴html
cnpm i html-webpack-plugin webpack-dev-server -D
配置文件
一、.babelrcnode
{ "presets": [ "@babel/preset-env", ] }
二、package.jsonwebpack
{ "name": "web-demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build": "webpack", "watch": "webpack --watch", "dev": "webpack-dev-server --open" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.9.0", "@babel/preset-env": "^7.9.0", "babel-loader": "^8.1.0", "css-loader": "^3.4.2", "file-loader": "^6.0.0", "html-webpack-plugin": "^4.0.3", "less": "^3.11.1", "less-loader": "^5.0.0", "style-loader": "^1.1.3", "url-loader": "^4.0.0", "webpack": "^4.42.1", "webpack-cli": "^3.3.11", "webpack-dev-server": "^3.10.3" } }
三、webpack.config.jsweb
'use strict' const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin') const webpack = require('webpack'); module.exports = { // 文件監聽 watch: true, watchOptions: { //默認爲空,設置不監聽的文件或者文件夾,支持正則匹配 ignored: /node_modules/, //監聽到變化發生後會等300ms再去執行,默認300ms aggregateTimeout: 300, //設置輪詢文件是否變化時間,默認每秒問1000次 poll: 1000 }, // 打包入口 entry: { index: './src/index.js', }, // 指定輸出地址及打包出來的文件名 output: { path: path.join(__dirname, 'dist'), filename: 'index.js' }, plugins: [ // 自動生成基本的 html 頁面 new HtmlWebpackPlugin({ title: 'leaningwebpack', // 文件的標題 filename: 'webpack-index.html', // 文件名 favicon: 'src/demo.png' // 網頁圖標 }), // 熱更新 new webpack.HotModuleReplacementPlugin() ], devServer: { contentBase: './dist', hot: true }, module: { rules: [ { test: /.js$/, use: 'babel-loader', // 忽略依賴包 exclude: /node_modules/ }, { test: /.css$/, // 執行的時候是先加載css-loader,將css解析好後再將css傳遞給style-loader use: [ 'style-loader', 'css-loader', ] }, { test: /.less$/, use: [ 'style-loader', 'css-loader', 'less-loader' ] }, { test: /.(jpg|png|gif|jpeg)$/, use: [{ loader: 'url-loader', options: { // 若是圖片大小小於這個值,就會被打包爲base64格式 limit: 160000, name: 'imgs/[name].[hash].[ext]' } }] } ] }, // 開發環境 mode: 'production', }