创建项目可以直接用cli构建,命令行敲几下就完成了,但是为了加深对webpack的理解,方便以后能够灵活运用webpack,还是有必要学习下如何手写webpack配置
初始化目录结构
// 生成tsconfig.json和package.json文件
npm init -y
tsc --init // 没有tsc的话,要先执行 npm i -g typescript
手动新建目录,和cli保持一致
修改package.json脚本
"scripts": {
"dev": "web-dev-server",
"build": "webpack"
}
安装依赖包
"devDependencies": {
"clean-webpack-plugin": "^4.0.0",
"html-webpack-plugin": "^5.5.0",
"less": "^4.1.3",
"less-loader": "^11.0.0",
"style-loader": "^3.3.1",
"typescript": "^4.8.3",
"ts-loader": "^9.3.1",
"vue-loader": "^17.0.0",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.11.0"
}
public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app"></div>
</body>
</html>
编写main.ts
import { createApp } from 'vue'
import App from './App.vue'
import './assets/main.less'
const app = createApp(App)
app.mount('#app')
编写App.vue
<template>
<div>
hello, {{name}}
</div>
</template>
<script setup lang="ts">
import {ref} from 'vue'
const name = ref<string>('bouc')
console.log('name:', name)
</script>
配置vue类型声明文件
declare module "*.vue" {
import { DefineComponent } from "vue"
const component: DefineComponent<{}, {}, any>
export default component
}
image.png
配置webpack.config.js
onst { Configuration } = require('webpack')
const path = require('path')
const htmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const { VueLoaderPlugin } = require('vue-loader/dist/index');
const FriendlyErrorsWebpackPlugin = require("friendly-errors-webpack-plugin");
/**
* @type {Configuration} //配置智能提示
*/
const config = {
mode: "development",
entry: './src/main.ts', //入口文件
output: {
filename: "[hash].js",
path: path.resolve(__dirname, 'dist') //出口文件
},
module: {
rules: [
{
test: /\.vue$/, //解析vue 模板
use: "vue-loader"
},
{
test: /\.less$/, //解析 less
use: ["style-loader", "css-loader", "less-loader"],
},
{
test: /\.css$/, //解析css
use: ["style-loader", "css-loader"],
},
{
test: /\.ts$/, //解析ts
loader: "ts-loader",
options: {
configFile: path.resolve(process.cwd(), 'tsconfig.json'),
appendTsSuffixTo: [/\.vue$/]
},
}
]
},
plugins: [
new htmlWebpackPlugin({
template: "./public/index.html" //html模板
}),
new CleanWebpackPlugin(), //打包清空dist
new VueLoaderPlugin(), //解析vue
new FriendlyErrorsWebpackPlugin({
compilationSuccessInfo:{ //美化样式
messages:['You application is running here http://localhost:9001']
}
})
],
resolve: {
alias: {
"@": path.resolve(__dirname, './src') // 别名
},
extensions: ['.js', '.json', '.vue', '.ts', '.tsx'] //识别后缀
},
stats:"errors-only", //取消提示
devServer: {
proxy: {},
port: 9001,
hot: true,
open: true,
},
externals: {
vue: "Vue" //CDN 引入
},
}
module.exports = config
执行npm run dev
最终效果:
网友评论