创建方式1
1.使用vite创建vue项目,需要将vue的脚手架升级为5+版本,注意升级后不会向下兼容vue2的语法创建项目的方法
2.升级vue脚手架:npm install vue@next 或 yarn global add @vue/cli
3.创建新项目
npm创建
npm init vite@latest vue3-project --template vue
cd vue3-project
npm install
npm run dev
yarn创建
yarn create vite vue3-project --template vue
cd vue3-project
yarn
yarn dev
查看入口文件main.js
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
创建Vue的方式变了,原来是new Vue来初始化Vue,但在Vue3.0中,修改为了通过createApp的方式,具体说明查看官方文档vue3官网...
创建方式2
1.直接安装vite
npm i -g create-vite-app
2.创建项目(注意vite和vitejs/plugin-vue的版本)
create-vite-app vue3-project
cd vue3-project
yarn
yarn add vite@2.7.2
yarn add @vitejs/plugin-vue@2.3.3
yarn add typescript
yarn dev
3.配置ts环境
在项目根目录创建文件:tsconfig.json
{
"compilerOptions": {
"baseUrl": "./",
"target": "esnext",
"useDefineForClassFields": true,
"module": "esnext",
"moduleResolution": "node",
"strict": true,
"allowJs": true,
"jsx": "preserve",
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"lib": ["esnext", "dom"],
"paths": {
"@/*": ["src/*"],
"@components/*": ["src/components/*"]
}
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}
在项目根目录下新建vite.config.ts文件
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
base: './',
resolve: {
alias: {
'@': '/src',
'@components': '/src/components',
},
},
build: {
sourcemap: true,
terserOptions: {
compress: {
//生产环境移除console.log
drop_console: true,
drop_debugger: true,
},
},
},
server: {
host: true,
proxy: {
},
},
});
修改src/main.js为src/main.ts;并修改引入html的文件名
在src下创建env.d.ts文件(声明各种变量的文件)
/// <reference types="vite/client" />
declare module '*.vue' {
import { DefineComponent } from 'vue';
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types
const component: DefineComponent<{}, {}, any>;
export default component;
}
declare module 'qs';
interface Window {
// naiveui 消息框
$message: any;
}
初始化项目就完成了...
如果所有步骤都完成了,tsconfig.json 还报模块找不到的错误,关闭编辑器重新打开让编辑器重新读取文件