创建vue2项目和基本配置

vue   2025-03-27 11:03   39   1  

一、创建 Vue 2 项目

1. 安装 Vue CLI 脚手架

bashnpm install -g @vue/cli# 或使用 yarnyarn global add @vue/cli

2. 创建 Vue 2 项目

由于 Vue CLI 4+ 默认使用 Vue 3,需通过以下方式创建 Vue 2 项目:

bashvue create my-project
  • 在提示中选择 Manually select features,然后勾选以下配置:

    markdown◉ Babel◉ Router
    ◉ Vuex
    ◉ CSS Pre-processors
    ◉ Linter / Formatter
  • 选择 Vue 2 版本。

  • 其他配置按需选择(如 ESLint 规则、CSS 预处理器等)。

二、项目基本配置

1. 配置文件 vue.config.js

在项目根目录创建 vue.config.js,常用配置如下:

javascriptmodule.exports = {  publicPath: process.env.NODE_ENV === 'production' ? '/my-project/' : '/', // 部署路径  outputDir: 'dist', // 打包输出目录  assetsDir: 'static', // 静态资源目录  lintOnSave: process.env.NODE_ENV !== 'production', // 生产环境禁用 ESLint  devServer: {    port: 8080, // 开发服务器端口    proxy: {      '/api': {        target: 'http://api.example.com', // 代理目标地址        changeOrigin: true,        pathRewrite: { '^/api': '' }      }    }  },  configureWebpack: {    resolve: {      alias: {        '@': path.resolve(__dirname, 'src') // 配置路径别名      }    }  }};

2. 安装常用依赖

bashnpm install axios sass sass-loader element-ui --save# 或使用 yarnyarn add axios sass sass-loader element-ui

3. 全局引入 UI 库(以 Element UI 为例)

在 src/main.js 中添加:

javascriptimport ElementUI from 'element-ui';import 'element-ui/lib/theme-chalk/index.css';Vue.use(ElementUI);

4. 配置路由(src/router/index.js

javascriptimport Vue from 'vue';import VueRouter from 'vue-router';import Home from '@/views/Home.vue';Vue.use(VueRouter);const routes = [  { path: '/', name: 'Home', component: Home },  { path: '/about', name: 'About', component: () => import('@/views/About.vue') }];const router = new VueRouter({  mode: 'history', // 使用 HTML5 History 模式  base: process.env.BASE_URL,  routes});export default router;

5. 配置 Vuex(src/store/index.js

javascriptimport Vue from 'vue';import Vuex from 'vuex';Vue.use(Vuex);export default new Vuex.Store({  state: {    count: 0  },  mutations: {    increment(state) {      state.count++;    }  },  actions: {    incrementAsync({ commit }) {      setTimeout(() => commit('increment'), 1000);    }  }});

三、目录结构说明

markdown├── public              # 静态资源(直接复制到输出目录)├── src
│   ├── assets          # 静态资源(如图片、字体)
│   ├── components      # 公共组件
│   ├── views           # 页面级组件
│   ├── router          # 路由配置
│   ├── store           # Vuex 状态管理
│   └── main.js         # 入口文件
├── .eslintrc.js        # ESLint 配置
├── babel.config.js     # Babel 配置
└── package.json        # 依赖管理

四、常用命令

bashnpm run serve     # 启动开发服务器npm run build     # 生产环境打包npm run lint      # 代码格式检查和修复

五、注意事项

  1. 兼容性:在 babel.config.js 或 package.json 中配置 browserslist,确保代码兼容目标浏览器。

  2. 环境变量:在项目根目录创建 .env.development 和 .env.production 定义环境变量(前缀 VUE_APP_)。

  3. 代码规范:在 .eslintrc.js 中自定义 ESLint 规则,或使用 prettier 统一代码风格。

通过以上步骤,即可完成 Vue 2 项目的创建和基础配置。


博客评论
匿名用户
说:

期待继续分享

1
发表评论
说明:请文明发言,共建和谐网络,您的个人信息不会被公开显示。