前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >vite新建vue3项目及安装插件笔记

vite新建vue3项目及安装插件笔记

作者头像
wade
发布2023-09-01 09:12:31
4290
发布2023-09-01 09:12:31
举报
文章被收录于专栏:coding个人笔记coding个人笔记
新建项目

新建项目vite 官网命令:

代码语言:javascript
复制
npm create vite@latest
配置 alias 别名

先安装依赖:

代码语言:javascript
复制
npm install -D @types/node

安装了才能使用 import { resolve } from 'path';,否则会报错: vite Cannot find module 'path' or its corresponding type declarations.

vite.config.ts 增加 resolve 配置:

代码语言:javascript
复制
import { resolve } from 'path';

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src'),
    },
  }
})

tsconfig.json 新增配置:

代码语言:javascript
复制
"baseUrl": ".", // Required for path aliases
"paths": {
  "@/*": ["src/*"]
},
安装 router

官网

代码语言:javascript
复制
npm install vue-router@4

//新建 router/index.ts
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/home',
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('@/views/Home.vue'),
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('@/views/About.vue'),
  },
  {
    path: '/product',
    name: 'Product',
    component: () => import('@/views/Product.vue'),
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});
export default router;

//main.ts
import Router from '@/router';

createApp(App).use(Router).mount('#app');

//使用
import { useRouter, useRoute } from 'vue-router';

const router = useRouter();
const route = useRoute();

router.push({ path: '/product', query: { entryId: entryId.value } });
router.push(path: '/product');

route.query.entryId

最基础的用法,动态路由,权限之类的,提供的 API 完全够用。

安装 Pinia

官网

代码语言:javascript
复制
npm install pinia

//main.ts
import { createPinia } from "pinia";

const pinia = createPinia();

createApp(App).use(pinia);

//新建stores/home.ts
import { defineStore } from 'pinia'

export const useHomeStore = defineStore('home', {
  state: () => ({ count: 0 }),
  actions: {
    increment() {
      this.count++
    },
  },
})

//使用
<div>Home {{ homeStore.count }}</div>

import { useHomeStore } from "@/stores/home";

const homeStore = useHomeStore();

正常来说是够用了,额外的可以到官网看看,还是有蛮多复杂场景的一些便利用法。

安装 sass
代码语言:javascript
复制
npm install sass

<style scoped lang="scss"></style>

这边 lang 使用 scss,scss 是 sass 3 引入的新语法。

vite.config.js 新增配置,跟 plugin/resolve/server 平级:

代码语言:javascript
复制
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: '@use  "@/assets/css/common.scss" as *;',
      },
    },
  },

  //common.scss
  $redColor: #D63933;
  $blueColor: #1F8BEA;

  //app.vue
  <div class="test">
    <span>sass avaliable</span>
    <p>sass avaliable</p>
  </div>

  <style scoped lang="scss">
  .test {
    span {
      color: $redColor;
    }
    p {
      color: $blueColor;
    }
  }
  </style>

有时候我们想要对一些引入的 UI 做一些初始化,新建一个 scss,比如 elementReset.scss,在 commom.scss 引入:

代码语言:javascript
复制
@import 'elementReset.scss';

也可以自定义一些常用的 css,下面是自动编译自适应使用:

代码语言:javascript
复制
$designWidth: 360;
$designHeight: 800;

@use "sass:math";

@function vw($px) {
  @return math.div($px, $designWidth) * 100vw;
}

@function vh($px) {
  @return math.div($px, $designHeight) * 100vh;
}

@function fs($px) {
  @return math.div($px, $designHeight) * 100vh;
}

@for $i from 1 through 50{
  .pd-#{$i} {
    padding: vw($i * 1);
  }
  .pt-#{$i} {
    padding-top: vh($i * 1);
  }
  .pb-#{$i} {
    padding-bottom: vh($i * 1);
  }
  .pl-#{$i} {
    padding-left: vw($i * 1);
  }
  .pr-#{$i} {
    padding-right: vw($i * 1);
  }

  .mg-#{$i} {
    margin: vw($i * 1);
  }
  .mt-#{$i} {
    margin-top: vh($i * 1);
  }
  .mb-#{$i} {
    margin-bottom: vh($i * 1);
  }
  .ml-#{$i} {
    margin-left: vw($i * 1);
  }
  .mr-#{$i} {
    margin-right: vw($i * 1);
  }

  .fs-#{$i}{
    font-size: vh($i);
  }
}

有一点要注意,@use "sass:math";最好放在最前面,否则报错@use rules must be written before any other rules.

安装 tailwindcss

英文文档 中文文档 选择 Using PostCSS,解释是与构建工具集成的最无缝的方式 is the most seamless way to integrate it with build tools like webpack, Rollup, Vite, and Parcel.

第一步 安装依赖:

代码语言:javascript
复制
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init

第二步 新增 tailwindcss and autoprefixe 到 postcss.config.js 文件: 根目录新建 postcss.config.js 文件:

代码语言:javascript
复制
export default {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  }
}

要注意,项目的 package.json 里面"type": "module",所以要改成 ES moduel 的方式。

第三步 tailwind.config.js 文件:

代码语言:javascript
复制
export default {
  content: ["./src/**/*.{html,js,vue}"],
  theme: {
    extend: {},
  },
  plugins: [],
}

要注意,content 官网没有 vue,因为是 vue 项目,所以要加上 vue,否则不生效。

第四步 新建一个 scss 文件,因为使用了 sass,在 common.scss 新增代码:

代码语言:javascript
复制
//common.scss

@tailwind base;
@tailwind components;
@tailwind utilities;

//test
<p class="bg-red-500">Hello world!</p>
安装 vue-i18n 国际化

安装依赖:

代码语言:javascript
复制
npm i vue-i18n

新建文件夹 i18n:

代码语言:javascript
复制
//新建index.ts
import { createI18n } from 'vue-i18n';
import { getItem } from '@/utils/utils';
import en from './en';
import zh from './zh';

export const defaultLocale = getItem('language') || 'en-US';

const i18n = createI18n({
  legacy: false,
  fallbackLocale: 'en-US',
  globalInjection: true,
  silentFallbackWarn: true,
  messages: {
    'en-US': en,
    'zh-US': zh,
  },
});

export default i18n;

//en.ts
export default {
  common: {
    test: 'test',
  }
}

//zh.ts
export default {
  common: {
    test: '测试',
  }
}

//main.ts
import i18n from '@/lang';

createApp(App).use(i18n).mount('#app');

//使用
<p>{{ $t(`common.test`) }}</p>

import i18n from '@/i18n';
i18n.global.t('common.test');

//修改语言
i18n.global.locale.value = 'zh-US';

如果有报错:

代码语言:javascript
复制
Could not find a declaration file for module 'vue-i18n'. 'c:/Users/37915/Desktop/mydata/myproject/yl-official-web/node_modules/vue-i18n/dist/vue-i18n.esm-bundler.js' implicitly has an 'any' type.
  There are types at 'c:/Users/37915/Desktop/mydata/myproject/yl-official-web/node_modules/vue-i18n/dist/vue-i18n.d.ts', but this result could not be resolved when respecting package.json "exports". The 'vue-i18n' library may need to update its package.json or typings.ts(7016)

是因为 typescript 版本大于 5,moduleResolution 是 bundler,可以安装最新的 npm install vue-i18n@next,只是还是 beta 阶段。目前的几个解决方案可以 GitHub 上面看看。新版的都得加-US,否则会有警告。

安装 element-plus

安装依赖:

代码语言:javascript
复制
npm install element-plus --save

//选择按需导入,官网推荐
npm install -D unplugin-vue-components unplugin-auto-import

// vite.config.ts
import { defineConfig } from 'vite'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

export default defineConfig({
  // ...
  plugins: [
    // ...
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [ElementPlusResolver()],
    }),
  ],
})

//测试
<el-button>我是 ElButton</el-button>

如果有下面的报错,是因为用了 typescript5,且配置的 moduleResolution 是 bundler,GitHub 有人提了 issue,但是还没修复发版,也是奇怪 vite 新建项目用了最新的,element-plus 没有紧跟上:

代码语言:javascript
复制
Module '"element-plus"' has no exported member 'ElMessage'. Did you mean to use 'import ElMessage from "element-plus"' instead?ts(2614)

还有一个要注意的点:

代码语言:javascript
复制
You need to manually import the styles if you're using unplugin-element-plus and only used the component API.

Example:

import 'element-plus/es/components/message/style/css'
import { ElMessage } from 'element-plus'

使用 unplugin-element-plus 自动导入,使用 ElMessage、ElLoading 等组件,需要手动导入样式。

使用了 unplugin-auto-import,还可以自动导入 vue、vue-router、element 的 icon 等,需要什么配置什么:

代码语言:javascript
复制
imports:["vue"],
dts:'src/auto-import.d.ts',

安装了 tailwindcss 会导致 element 的 button 样式缺失了,解决方案一个是先引入 tailwind 再引入 element 的,但是自动引入的不好处理,另外就是在 tailwind.config.js 把缺失的补全,可能会好一点,还有一种生效了,但是不知道有没有另外的问题:

代码语言:javascript
复制
// tailwind.config.js
plugins: [
    function ({ addBase }) {
        addBase({
            ".el-button": {
                "background-color": "var(--el-button-bg-color,var(--el-color-white))"
            }
        });
    }
]

// tailwind.config.js
plugins: [],
corePlugins: {
  preflight: false,
}

自定义主题,官网给了很多方法,看了很久,也试了很多次,发现全部替换都不生效,一直在 additionalData:这个配置里面引入,看 sass 变量混合之类的问题,忽略了一句:然后在你的项目入口文件中,导入这个样式文件以替换 Element Plus 内置的 CSS:

代码语言:javascript
复制
//新建element.scss
@forward 'element-plus/theme-chalk/src/common/var.scss' with (
    $colors: (
        //主题色对应颜色设置
        'primary': (
            'base': #ff7ad9,
        ),
    ),
);

@use "element-plus/theme-chalk/src/index.scss" as *;

//在main.ts引入
import '@/assets/css/element.scss';

至于其他方法,想想还是不试了,我觉得官方给的文档还是不够好,总有一些要去试,也有可能是本人看文档能力不行?

不知道是不是先入为主的观念,vue 就是使用 element,antd 用过一次,感觉是比 element 好,安装 antd 就不试了。

tips:后面安装了一些其他东西,不知道为什么主题色不生效了,被覆盖了,在 main.ts 用 import()定时器引入才有用,没找到是因为配置哪个导致的。

tips

有时候安装了依赖,typescript 会报错,修改编辑器和项目的 typescript 版本,ctrl+shift+p,然后输入 typescript,选择版本,使用 work space 的版本。

这次新建项目,因为 typescript 版本是 5.x,"moduleResolution": "bundler",出现了一些兼容性的问题,如果出现一些以前不会,可以看看是否是这个影响。

安装过程如果有一些报错警告,通过 GitHub 去搜索 issue,比较容易找到答案。

以后有其他插件安装也可以在这边记录一下,之后再新建项目就会容易很多了。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2023-06-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 coding个人笔记 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 新建项目
  • 配置 alias 别名
  • 安装 router
  • 安装 Pinia
  • 安装 sass
  • 安装 tailwindcss
  • 安装 vue-i18n 国际化
  • 安装 element-plus
  • tips
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档