webpack4架构的搭建和vue单组件的应用
首先进入安装目录的文件夹,输入npm init初始化package.json:
本地安装webpack和webpack-cli:
npm install webpack webpack-cli -D//-D是指开发环境需要,上线环境不需要;
创建入口文件,配置packet.json进行打包处理
在webpack4.0中默认将./src/index.js作为入口,创建./src/index.js并在正文中输入:console.log("哈哈哈");
并在package.json中配置脚本:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build":"webpack"
},
执行命令:
npm run build
编译成功后,会自动创建./dist/index.js
配置webpack:
配置webpack.config.js:
- entry:配置入口文件的地址
- output:配置出口文件的地址
- module:配置模块,主要用来配置不同文件的加载器
- plugins:配置插件
- devServer:配置开发服务器
-
var path = require('path');//node的模块 module.exports = { entry:'./src/index.js', // 入口 output:{ filename:'build.js', // 这个路径必须是绝对路径 path: path.resolve('./dist') }, // 出口 devServer:{ contentBase:'./dist', //配置开发服务运行时的文件根目录 port:8080, compress:true,// 服务器压缩 open:true,// 自动打开浏览器 // hot:true//热更新 },// 开发服务器 module:{}, // 模块配置 plugins:[], // 插件的配置 mode:'development', // 可以更改模式 resolve:{}, // 配置解析 }
配置开发服务器:
npm i webpack-dev-server –D
利用devserver配置服务器相关参数:
devServer:{
contentBase:'./dist',
port:8081,
compress:true,// 服务器压缩
open:true,// 自动打开浏览器
// hot:true//热更新
},// 开发服务器
重新配置配置webpack.config.js:
+ "scripts": {
+ "build": "webpack --mode development",
+ "dev": "webpack-dev-server --open --mode development "
+ }//开启本地服务 npm run dev
自动产出HTML文件:
npm i html-webpack-plugin -D
- minify 是对html文件进行压缩,removeAttrubuteQuotes是去掉属性的双引号
- hash 引入产出资源的时候加上哈希避免缓存
- template 模版路径
//自动产出HTML文件,并在里面引入产出后的资源
plugins: [
new HtmlWebpackPlugin({
minify: {
removeAttributeQuotes:true
},
hash: true,
template: './src/index.html',
filename:'index.html'
})],
压缩CSS文件
安装依赖:
- npm i mini-css-extract-plugin css-loader --save-dev
创建./index.css
配置webpack.config.js:
var path = require('path');//node的模块\
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: {
index: './src/index.js',
main: './src/main.js',
xiix: './src/xixi.js'
},
// 入口
output: {
filename: '[name].[hash].js',
// 这个路径必须是绝对路径
path: '/dist'
}, // 出口
devServer: {
contentBase: './dist',
port: 8082,
compress: true,// 服务器压缩
open: true,// 自动打开浏览器
// hot:true//热更新
},// 开发服务器
module: {
rules:[{
test:/\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"]
}
]
}, // 模块配置
//自动产出HTML文件,并在里面引入产出后的资源
plugins: [
new HtmlWebpackPlugin({
template: './index.html',
filename: 'index.html'
}),
new MiniCssExtractPlugin({
filename:"[name].css",
chunkFilename:"[id].css"
})
],
mode: 'development', // 可以更改模式
resolve: {}, // 配置解析
}
引用css文件:
import style from '../index.css'