vite+vue3+typeScript项目搭建

目录

1.搭建项目

2.安装typescript、router、axios插件

3.vite.config.ts配置

4.tsconfig.json配置

5.将main.js改为main.ts , index.html里的main.js改为maim.ts

6.解决main.ts中引入App.vue报错问题


1.搭建项目

使用npm

npm init vite-app  projectName
cd projectName
npm install
npm run dev

使用yarn

yarn create vite-app projectName
cd projectName
yarn
yarn dev

2.安装typescript、router、axios插件

使用npm安装

npm install vue-router@next axios --save
npm install typescript --save-dev

使用yarn安装

yarn add vue-router@next axios
yarn add typescript --dev

3.vite.config.ts配置

 在项目第一层创建vite.config.ts文件,文件配置如下:

import path from "path";
const pathResolve = (pathStr: string) => {
  return path.resolve(__dirname, pathStr);
}

const config = {
  base: './',//在生产中服务时的基本公共路径。@default '/'
  alias: {
    '/@/': pathResolve('./src'),
  },
  outDir: 'vite-init',//构建输出将放在其中。会在构建之前删除旧目录。@default 'dist'
  minify: 'esbuild',//构建时的压缩方式
  hostname: 'localhost',//本地启动的服务地址
  port: '8800',//服务端口号
  open: false,//启动服务时是否在浏览器打开
  https: false,//是否开启https
  ssr: false,//是否服务端渲染
  optimizeDeps: {// 引入第三方的配置
    include: ['axios']
  },
  // proxy: {//代理配置
  //   '/api': {
  //     target: 'http://xx.xx.xx.xx:xxxx',
  //     changeOrigin: true,
  //     ws: true,
  //     rewrite: (path: string) => { path.replace(/^\/api/, '') }
  //   }
  // }
}
module.exports = config;

4.tsconfig.json配置

 在项目的第一层新建tsconfig.json文件,文件配置如下:

{
  "compilerOptions": {
    "target": "ES5",//指定ECMAScript的目标版本:'ES3'(默认),'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020',或'ESNEXT'。
    "module": "commonjs",//指定模块代码生成:'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020',或'ESNext'。
    "strict": true,//是否启用所有严格的类型检查选项。
    "baseUrl":"./",//用于解析非绝对模块名称的基本目录。
    "paths": {
      "/@/*": ["./src/*"]
    },  
    "noImplicitAny": true, //对于隐含有'any'类型的表达式和声明引发错误。
    "esModuleInterop": true, //通过为所有导入创建名称空间对象,实现CommonJS和ES模块之间的互操作性。意味着“allowSyntheticDefaultImports”。
    "experimentalDecorators": true, //支持对ES7装饰器的实验性支持。
    "skipLibCheck": true, //跳过声明文件的类型检查。
    "forceConsistentCasingInFileNames": true //禁止对同一文件使用大小写不一致的引用。
  }
}

5.将main.js改为main.ts , index.html里的main.js改为maim.ts

6.解决main.ts中引入App.vue报错问题

报错如下:

 解决方法:

在src目录下新建.d.ts文件,文件名可随意,例如:shim.d.ts

.d.ts文件内容如下:

declare module "*.vue" {
    import { Component } from "vue";
    const  component : Component;
    export default component;
}

猜你喜欢

转载自blog.csdn.net/baidu_39009276/article/details/122965556