上一篇說了webpack 手動搭建模塊虚汛,在開發(fā)中都是腳手架搭建好的自動化配置媳维。那么怎么用webpack搭建個像腳手架那樣的呢裕便。主要有三步暑椰。
- 手動搭建模塊
- 自動生成html模板
- 配置webpack-dev-server的本地服務(wù)
手動搭建模塊在上個文章說了。
點(diǎn)我查看自動生成html模板现使,比較簡單低匙,就是webpack的HtmlWebpackPlugin插件。這個插件不用另外安裝碳锈,它存在于node_modules中顽冶。直接在webpack.config.js中使用即可
const HtmlWebpackPlugin = require('html-webpack-plugin');
...
new HtmlWebpackPlugin({
template: "index.html"
}),
- webpack-dev-server是啟動本地服務(wù)的關(guān)鍵。安裝的時(shí)候版本不同可能會有沖突售碳,所以最好指定版本安裝强重。
npm install webpack-dev-server@3.11.2 --save--dev
npm install webpack-cli@3.3.2 -g --save--dev
另外還需要在package.json中加入
// 在package.json 修改
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server",
"build": "webpack --mode=development"
},
在webpack.config.js中添加
devServer: {
contentBase: path.join(__dirname, 'dist'), //本地服務(wù)根文件
inline: true ,//實(shí)時(shí)刷新
port: 8080
}
最后運(yùn)行绞呈。
npm run dev
運(yùn)行起來后直接在瀏覽器中輸入localhost:8080 即可。而且修改東西后會自動更新頁面间景。不用在npm run build一直輸入命令刷新了佃声。
完整配置
webpack.config.js
const path = require('path')
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
//一旦依賴node 就npm init
module.exports = {
entry : './src/main.js', //入口文件
output : {
path : path.resolve(__dirname,'dist'), //輸出目錄
filename : 'bundle.js' //輸出文件名
},
mode: 'production',
resolve : {
//省略后綴名
extensions : ['.js','.css','.vue'],
alias : {
'@':path.join(__dirname,'./src'),//這樣 @就表示根目錄src這個路徑
vue: 'vue/dist/vue.js',
}
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
},
{
test: /\.vue$/,
loader: 'vue-loader',
// options:vueloaderOptions(isDev),
// exclude:/node_modules/
},
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
]
},
plugins: [
new webpack.BannerPlugin("版本歸聞居士所有."),
new HtmlWebpackPlugin({
template: "index.html"
}),
],
devServer: {
contentBase: path.join(__dirname, 'dist'), //本地服務(wù)根文件
inline: true ,//實(shí)時(shí)刷新
port: 8080
}
}
package.json配置
{
"name": "day06",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server",
"build": "webpack --mode=development"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.13.10",
"@babel/preset-env": "^7.13.10",
"babel-loader": "^8.2.2",
"css-loader": "^5.1.2",
"html-webpack-plugin": "^5.3.1",
"style-loader": "^2.0.0",
"vue": "^2.6.12",
"vue-loader": "^14.1.1",
"vue-template-compiler": "^2.6.12",
"webpack-dev-server": "^3.11.2",
"webpack-cli": "^3.3.2"
},
"dependencies": {
"vue": "^2.6.12"
}
}