如何从0开始搭建最新版本webpack5 + vue3 + ts + axios + vuex + elementPlus 项目
时间: 2025-08-25 07:00:40 AIGC 浏览: 15
<think>我们正在搭建一个使用Webpack 5、Vue 3、TypeScript、Axios、Vuex和Element Plus的项目。以下步骤将指导你完成搭建过程。
### 1. 初始化项目
创建项目目录并初始化npm:
```bash
mkdir vue3-webpack5-project
cd vue3-webpack5-project
npm init -y
```
### 2. 安装Webpack和相关工具
安装Webpack 5及其命令行工具:
```bash
npm install --save-dev webpack webpack-cli webpack-dev-server
```
### 3. 安装Vue 3
安装Vue 3及其编译器:
```bash
npm install vue@next
npm install --save-dev vue-loader@next @vue/compiler-sfc
```
### 4. 安装TypeScript
安装TypeScript及相关类型声明和加载器:
```bash
npm install --save-dev typescript ts-loader
npm install --save-dev @types/node @types/webpack
```
### 5. 安装Axios
安装Axios库:
```bash
npm install axios
```
### 6. 安装Vuex 4
安装Vuex 4(与Vue 3兼容):
```bash
npm install vuex@next
```
### 7. 安装Element Plus
安装Element Plus及其图标库:
```bash
npm install element-plus
npm install @element-plus/icons-vue
```
### 8. 配置TypeScript
创建`tsconfig.json`文件:
```json
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"moduleResolution": "node",
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
},
"types": ["webpack-env"]
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
"exclude": ["node_modules"]
}
```
### 9. 配置Webpack
创建`webpack.config.ts`文件(使用TypeScript配置):
```typescript
import path from 'path';
import { Configuration } from 'webpack';
import { VueLoaderPlugin } from 'vue-loader';
import HtmlWebpackPlugin from 'html-webpack-plugin';
const config: Configuration = {
mode: 'development',
entry: './src/index.ts',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
resolve: {
extensions: ['.ts', '.js', '.vue', '.json'],
alias: {
'@': path.resolve(__dirname, 'src')
}
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/,
options: {
appendTsSuffixTo: [/\.vue$/]
}
},
{
test: /\.(scss|css)$/,
use: ['style-loader', 'css-loader', 'sass-loader']
},
{
test: /\.(png|jpe?g|gif|svg)$/i,
type: 'asset/resource'
}
]
},
plugins: [
new VueLoaderPlugin(),
new HtmlWebpackPlugin({
template: './public/index.html'
})
],
devServer: {
static: {
directory: path.join(__dirname, 'public')
},
compress: true,
port: 9000,
hot: true
}
};
export default config;
```
注意:需要安装相关loader和插件:
```bash
npm install --save-dev html-webpack-plugin style-loader css-loader sass-loader sass file-loader
npm install --save-dev @types/html-webpack-plugin @types/webpack-dev-server
```
### 10. 创建项目结构
创建以下目录和文件:
```
├── public
│ └── index.html
├── src
│ ├── App.vue
│ ├── index.ts
│ ├── shims-vue.d.ts
│ ├── components
│ ├── store (Vuex store)
│ ├── api (Axios封装)
│ └── views
```
#### 10.1 `public/index.html`内容:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue3 Webpack5 Project</title>
</head>
<body>
<div id="app"></div>
</body>
</html>
```
#### 10.2 `src/shim-vue.d.ts`内容(解决Vue文件模块声明):
```typescript
declare module '*.vue' {
import { DefineComponent } from 'vue';
const component: DefineComponent<{}, {}, any>;
export default component;
}
```
#### 10.3 `src/index.ts`内容(入口文件):
```typescript
import { createApp } from 'vue';
import App from './App.vue';
import store from './store';
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';
import * as ElementPlusIconsVue from '@element-plus/icons-vue';
const app = createApp(App);
// 注册Element Plus图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component);
}
app.use(store);
app.use(ElementPlus);
app.mount('#app');
```
#### 10.4 `src/App.vue`内容(根组件):
```vue
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
name: 'App'
});
</script>
```
### 11. 封装Axios
在`src/api`目录下创建`request.ts`:
```typescript
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
class HttpRequest {
private instance: AxiosInstance;
constructor(config: AxiosRequestConfig) {
this.instance = axios.create(config);
this.interceptors();
}
private interceptors() {
// 请求拦截
this.instance.interceptors.request.use(
(config: AxiosRequestConfig) => {
// 可在此添加请求头等
return config;
},
(error: any) => {
return Promise.reject(error);
}
);
// 响应拦截
this.instance.interceptors.response.use(
(response: AxiosResponse) => {
// 对响应数据做处理
return response.data;
},
(error: any) => {
return Promise.reject(error);
}
);
}
public request<T = any>(config: AxiosRequestConfig): Promise<T> {
return this.instance.request(config);
}
public get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
return this.request<T>({ ...config, method: 'get', url });
}
public post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
return this.request<T>({ ...config, method: 'post', url, data });
}
// 其他方法(put, delete等)类似
}
export default HttpRequest;
```
### 12. 配置Vuex
在`src/store`目录下创建`index.ts`:
```typescript
import { createStore } from 'vuex';
export default createStore({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++;
}
},
actions: {
increment({ commit }) {
commit('increment');
}
},
modules: {
}
});
```
### 13. 添加脚本
在`package.json`中添加启动和构建脚本:
```json
"scripts": {
"dev": "webpack serve --config webpack.config.ts",
"build": "webpack --config webpack.config.ts --mode production"
}
```
### 14. 运行项目
```bash
npm run dev
```
现在,你的项目应该运行在 http://localhost:9000 。
### 常见问题
1. **Vue单文件组件类型支持**:确保在`tsconfig.json`中正确配置了`shims-vue.d.ts`。
2. **Element Plus按需引入**:如果需要按需引入,可以使用`unplugin-element-plus`等插件,但这里为了简便,我们全量引入了。
3. **Webpack配置**:如果遇到配置问题,检查`webpack.config.ts`中的loader顺序和插件。
### 总结
通过以上步骤,我们成功搭建了一个基于Webpack 5、Vue 3、TypeScript、Axios、Vuex和Element Plus的项目。这个配置可以作为基础模板,根据实际需求进行扩展。
§§相关问题§§
1. 如何优化Webpack 5构建性能?
2. Vue 3中如何使用Composition API与Vuex?
3. 如何实现Element Plus的按需引入?
4. 在TypeScript项目中如何更好地组织Vuex模块?
5. 如何配置Webpack支持多环境(开发、测试、生产)?</think>### 搭建 Webpack 5 + Vue 3 + TypeScript + Axios + Vuex + Element Plus 项目
#### 1. 初始化项目
```bash
mkdir vue3-webpack5-project
cd vue3-webpack5-project
npm init -y
```
#### 2. 安装核心依赖
```bash
# Webpack 5 核心
npm install --save-dev webpack webpack-cli webpack-dev-server webpack-merge
# Vue 3 相关
npm install vue@next
npm install --save-dev vue-loader@next @vue/compiler-sfc
# TypeScript 支持
npm install --save-dev typescript ts-loader @types/node @types/webpack
# Axios 网络请求
npm install axios
# Vuex 状态管理
npm install vuex@next
# Element Plus UI 库
npm install element-plus @element-plus/icons-vue
```
#### 3. 基础目录结构
```
├── public/
│ └── index.html
├── src/
│ ├── main.ts
│ ├── App.vue
│ ├── components/
│ ├── store/ # Vuex
│ ├── api/ # Axios封装
│ └── assets/
├── tsconfig.json
├── webpack.config.ts
└── package.json
```
#### 4. 关键配置文件
**tsconfig.json**:
```json
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"moduleResolution": "node",
"esModuleInterop": true,
"skipLibCheck": true,
"baseUrl": ".",
"types": ["webpack-env"],
"paths": {
"@/*": ["src/*"]
}
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.vue"]
}
```
**webpack.config.ts** (Webpack 5 配置):
```typescript
import path from 'path';
import { Configuration } from 'webpack';
import { VueLoaderPlugin } from 'vue-loader';
import HtmlWebpackPlugin from 'html-webpack-plugin';
const config: Configuration = {
mode: 'development',
entry: './src/main.ts',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
resolve: {
extensions: ['.ts', '.js', '.vue', '.json'],
alias: {
'@': path.resolve(__dirname, 'src')
}
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.tsx?$/,
loader: 'ts-loader',
options: {
appendTsSuffixTo: [/\.vue$/]
}
},
{
test: /\.(scss|css)$/,
use: ['style-loader', 'css-loader', 'sass-loader']
},
{
test: /\.(png|jpe?g|gif|svg)$/i,
type: 'asset/resource'
}
]
},
plugins: [
new VueLoaderPlugin(),
new HtmlWebpackPlugin({
template: './public/index.html'
})
],
devServer: {
static: {
directory: path.join(__dirname, 'public')
},
compress: true,
port: 8080,
hot: true
}
};
export default config;
```
#### 5. Vue 3 入口文件 (src/main.ts)
```typescript
import { createApp } from 'vue';
import App from './App.vue';
import store from './store';
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';
import * as ElementPlusIconsVue from '@element-plus/icons-vue';
const app = createApp(App);
// 注册Element Plus图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component);
}
app.use(store);
app.use(ElementPlus);
app.mount('#app');
```
#### 6. 封装 Axios (src/api/request.ts)
```typescript
import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
class HttpRequest {
private instance: AxiosInstance;
constructor(config: AxiosRequestConfig) {
this.instance = axios.create(config);
this.interceptors();
}
private interceptors() {
// 请求拦截
this.instance.interceptors.request.use(config => {
// 添加token等逻辑
return config;
});
// 响应拦截
this.instance.interceptors.response.use(response => {
return response.data;
}, error => {
return Promise.reject(error);
});
}
public request<T = any>(config: AxiosRequestConfig): Promise<T> {
return this.instance.request(config);
}
}
export default new HttpRequest({
baseURL: '/api',
timeout: 10000
});
```
#### 7. Vuex 配置 (src/store/index.ts)
```typescript
import { createStore } from 'vuex';
interface State {
count: number;
}
export default createStore<State>({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++;
}
},
actions: {
async fetchData({ commit }) {
// 使用封装的axios
const data = await request.get('/data');
commit('setData', data);
}
}
});
```
#### 8. 添加脚本命令 (package.json)
```json
"scripts": {
"dev": "webpack serve --config webpack.config.ts",
"build": "webpack --config webpack.config.ts --mode production"
}
```
#### 9. 运行项目
```bash
npm run dev
```
### 关键注意事项:
1. **Vue SFC 类型支持**:创建 `src/shims-vue.d.ts` 文件:
```typescript
declare module '*.vue' {
import { DefineComponent } from 'vue';
const component: DefineComponent<{}, {}, any>;
export default component;
}
```
2. **Element Plus 按需引入**(可选):
```bash
npm install -D unplugin-vue-components unplugin-auto-import
```
在 `webpack.config.ts` 中添加:
```typescript
import AutoImport from 'unplugin-auto-import/webpack';
import Components from 'unplugin-vue-components/webpack';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
// plugins 数组中添加:
AutoImport({
resolvers: [ElementPlusResolver()],
}),
Components({
resolvers: [ElementPlusResolver()],
}),
```
3. **SCSS 支持**:
```bash
npm install -D sass sass-loader
```
### 项目结构优化建议
```
src/
├── api/ # API请求封装
│ ├── modules/ # 模块化API
│ └── request.ts # Axios实例
├── assets/
├── components/
├── router/ # Vue Router
├── store/ # Vuex
│ ├── modules/ # Vuex模块
│ └── index.ts
├── types/ # 全局类型声明
├── utils/ # 工具函数
├── views/ # 页面组件
├── App.vue
└── main.ts
```
此配置实现了:
- Webpack 5 最新构建工具
- Vue 3 Composition API
- TypeScript 类型安全
- Axios 网络请求封装
- Vuex 状态管理
- Element Plus UI 组件库
- 开发/生产环境分离
[^1][^3]
阅读全文
相关推荐



















