Skip to content

Vue3-插件引入

@types/node类型声明包插件

  • 安装@types/node 类型声明包
JS
yarn add @types/node -D

作用:

是将 Node.js 的类型定义文件安装到 TypeScript 项目中,作为开发依赖(devDependency)添加。这样我们在使用Node.js的标准库模块时可以享受类型检查和代码补全的功能,也就是补全的作用。

unplugin-auto-import自动引入插件

认识

"esModuleInterop": true 是 TS配置中的一个选项,作用是使TypeScript在导入 ES 模块时,能够与 CommonJS 模块兼容

解决了在使用 CommonJS 模块时,如何正确地导入默认导出和命名导出的问题。

介绍

有时候我们在项目需要频繁的引入下面这种,如何做到直接全局使用呢

javascript
import { ref, computed } from 'vue';

🍎 方式一(额外封装引入)

javascript
import { ref, computed } from 'vue';

export const gRef = ref;
export const gComputed = computed;

然后再需要的地方进行引入

javascript
import { gRef, gComputed } from '@/utils/vueGlobal';

const count = gRef(0);
const double = gComputed(() => count.value * 2);

看到这里,你肯定懂了,这还不如我直接引入呢,直接丢弃

🍎 方式二(全局挂载到 app.config.globalProperties

javascript
// 全局挂载到 app.config.globalProperties

// ... 其他引入
import { ref, computed } from 'vue';

const app = createApp(App);

app.config.globalProperties.$ref = ref;
app.config.globalProperties.$computed = computed;

app.mount('#app');

在项目之中使用的时候

javascript
const count = this.$ref(0);
const double = this.$computed(() => count.value * 2);

这种方式倒是可以稍微考虑一下

🍎 方式三(unplugin-auto-import自动引入插件)

查看详细看我关于这个插件的解释文章

javascript
 // 没有引入之前直接使用报错
Uncaught (in promise) ReferenceError: ref is not defined

//引入以后直接使用
无输出

安装引入

☞ 安装插件

js
yarn add unplugin-auto-import -D

配置

☞兼容CommonJS模块导入路径配置

JS
"esModuleInterop": true,

☞ 在 vite.config.js 中进行配置

js
import AutoImport from 'unplugin-auto-import/vite'; // 自动导入插件

// ...其他配置
plugins: [
  AutoImport({
    imports: [
      'vue', // 自动引入 Vue 函数
      'vue-router', // 自动引入 vue-router 的函数
    ],
    dts: true,  // 生成类型声明文件
  }),
],


// 优化配置
plugins: [
  // ...其他插件
  AutoImport({
    imports: ['vue'], // 自动导入vue的API
    dts: 'src/auto-imports.d.ts', // 自动生成类型声明
  }),
],

报错处理

确保你的tsconfig.json文件下有如下配置

js
"esModuleInterop": true,

// 放置位置
{
  "compilerOptions": {
    "esModuleInterop": true,
    "moduleResolution": "node",
    "strict": true,
    "jsx": "preserve",
    "lib": ["esnext", "dom"]
  }
}

作用

使用 lodash(一个 CommonJS 模块),没有开启esModuleInterop

JS
import * as _ from 'lodash';

开启esModuleInterop后

JS
import _ from 'lodash';

Released under the MIT License.