Git Product home page Git Product logo

vite-auto-import-resolvers's Introduction

推荐

unplugin-auto-import 已经内置 dirs 选项,推荐优先使用

vite-auto-import-resolvers

unplugin-auto-importvite resolvers,主要处理 vite 项目本身的 api 按需自动引入。


README 🦉

简体中文 | English



动机 🐇

为了按需自动引入指定目录下模块的 api



基本使用 🦖

  1. 安装
npm i vite-auto-import-resolvers unplugin-auto-import -D
  1. 配置插件
// vite.config.js
import { defineConfig } from "vite";
import Vue from "@vitejs/plugin-vue";
import AutoImports from "unplugin-auto-import/vite";
import { dirResolver, DirResolverHelper } from "vite-auto-import-resolvers";

export default defineConfig({
  plugins: [
    Vue(),
    // 该辅助插件也是必需的 👇
    DirResolverHelper(),
    AutoImports({
      imports: ["vue"],
      resolvers: [dirResolver()],
    }),
  ],
});
  1. 之后 src/composables 下模块的默认导出将在项目中自动按需引入

例如 👇

// src/composables/foo.ts

export default 100;
// src/App.vue
<script setup>
	console.log(foo) // 输出100,而且是按需自动引入的
</script>

<template> Hello World!! </template>

进阶 🦕

强制前缀与后缀

import { defineConfig } from "vite";
import Vue from "@vitejs/plugin-vue";
import AutoImports from "unplugin-auto-import/vite";
import { dirResolver, DirResolverHelper } from "vite-auto-import-resolvers";

export default defineConfig({
  plugins: [
    Vue(),
    DirResolverHelper(),
    AutoImports({
      imports: ["vue"],
      resolvers: [
        dirResolver({ prefix: "use" }), // 强制前缀为 use
        dirResolver({
          target: "src/stores", // 目标目录,默认为 'src/composables'
          suffix: "Store", // 强制后缀为 Store
        }),
      ],
    }),
  ],
});

于是

  • src/composables 下只有 use 开头的模块会被按需加载
  • src/stores 下只有 Store 结尾的模块会被按需加载

例如 👇

// src/stores/counterStore.ts
const counter = ref(100);

export default () => {
  const inc = (v: number = 1) => (counter.value += v);
  return {
    inc,
    counter,
  };
};
<script setup lang="ts">
	// 这将按需自动引入
	const n = counterStore()
</script>

<template>
	<div @click="n.inc()">{{n.counter}}</div>
</template>


包含与排除

import { defineConfig } from "vite";
import Vue from "@vitejs/plugin-vue";
import AutoImports from "unplugin-auto-import/vite";
import { dirResolver, DirResolverHelper } from "vite-auto-import-resolvers";

export default defineConfig({
  plugins: [
    Vue(),
    DirResolverHelper(),
    AutoImports({
      imports: ["vue"],
      resolvers: [
        dirResolver({
          prefix: "use",
          include: ["foo"], // 即使 foo 模块不是以 use 开头也会被包含进来
          exclude: ["useBar"], // useBar 模块将始终被排除
        }),
      ],
    }),
  ],
});


规范路径

通过 normalize 可以控制最终路径的生成

import { defineConfig } from "vite";
import Vue from "@vitejs/plugin-vue";
import AutoImports from "unplugin-auto-import/vite";
import { dirResolver, DirResolverHelper } from "vite-auto-import-resolvers";

export default defineConfig({
  plugins: [
    Vue(),
    DirResolverHelper(),
    AutoImports({
      imports: ["vue"],
      resolvers: [
        dirResolver({
          normalize({ path, target, name }) {
            return path;
          },
        }),
      ],
    }),
  ],
});


自动生成按需 api 预设

在使用 unplugin-auto-imports 时,需要手动管理 imports 👇

import { defineConfig } from "vite";
import Vue from "@vitejs/plugin-vue";
import AutoImports from "unplugin-auto-import/vite";

export default defineConfig({
  plugins: [
    Vue(),
    AutoImports({
      imports: ["vue", "vue-router", "pinia"], // 手动管理
    }),
  ],
});

但有时候你可能需要去变动一些依赖,例如将 pinia 换成 vuex,这时如果配置未更改就会发生错误。同时如果你设置了未安装的包,这将造成无谓的性能消耗。

所以你能这样 👇

import { defineConfig } from "vite";
import Vue from "@vitejs/plugin-vue";
import AutoImports from "unplugin-auto-import/vite";
import { AutoGenerateImports } from "vite-auto-import-resolvers";

export default defineConfig({
  plugins: [
    Vue(),
    AutoImports({
      imports: AutoGenerateImports(), // 自动管理,只有对应的包有装时才会自动按需设置预设
    }),
  ],
});

默认支持列表

include 属性

  • vue
  • pinia
  • vuex
  • vitest
  • vue-i18n
  • vue-router
  • @vueuse/core
  • @vueuse/head
  • @nuxtjs/composition-api
  • preact
  • quasar
  • react
  • react-router
  • react-router-dom
  • svelte
  • svelte/animate
  • svelte/easing
  • svelte/motion
  • svelte/store
  • svelte/transition
  • vitepress
  • vee-validate

手动排除

当然你可以手动排除掉不想要的 👇

import { defineConfig } from "vite";
import Vue from "@vitejs/plugin-vue";
import AutoImports from "unplugin-auto-import/vite";
import { AutoGenerateImports } from "vite-auto-import-resolvers";

export default defineConfig({
  plugins: [
    Vue(),
    AutoImports({
      imports: AutoGenerateImports({
        exclude: ["pinia"], // pinia 将始终被排除
      }),
    }),
  ],
});


启发 🐳

resolvers 来源于 unplugin-auto-importissue 讨论 👉 How should I auto import composition functions



更多 🐃

更多项目工程实践可见 👉 tov-template



License 🐸

Made with markthree

Published under MIT License.


vite-auto-import-resolvers's People

Contributors

jbaubree avatar markthree avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

vite-auto-import-resolvers's Issues

在使用vite3版本的时候,会出现Dynamic require of "path" is not supported的错误

image
failed to load config from E:\Project\Vue3\xl-xling-admin\vite.config.ts error when starting dev server: Error: Dynamic require of "path" is not supported at file:///E:/Project/Vue3/xl-xling-admin/node_modules/.pnpm/[email protected]_v5xq3qlwvf4akn2un7a5tsc4oq/node_modules/vite-auto-import-resolvers/dist/index.mjs:1:775 at file:///E:/Project/Vue3/xl-xling-admin/node_modules/.pnpm/[email protected]_v5xq3qlwvf4akn2un7a5tsc4oq/node_modules/vite-auto-import-resolvers/dist/index.mjs:1:2352 at file:///E:/Project/Vue3/xl-xling-admin/node_modules/.pnpm/[email protected]_v5xq3qlwvf4akn2un7a5tsc4oq/node_modules/vite-auto-import-resolvers/dist/index.mjs:1:891 at file:///E:/Project/Vue3/xl-xling-admin/node_modules/.pnpm/[email protected]_v5xq3qlwvf4akn2un7a5tsc4oq/node_modules/vite-auto-import-resolvers/dist/index.mjs:2:32192 at file:///E:/Project/Vue3/xl-xling-admin/node_modules/.pnpm/[email protected]_v5xq3qlwvf4akn2un7a5tsc4oq/node_modules/vite-auto-import-resolvers/dist/index.mjs:1:891 at file:///E:/Project/Vue3/xl-xling-admin/node_modules/.pnpm/[email protected]_v5xq3qlwvf4akn2un7a5tsc4oq/node_modules/vite-auto-import-resolvers/dist/index.mjs:2:32554 at file:///E:/Project/Vue3/xl-xling-admin/node_modules/.pnpm/[email protected]_v5xq3qlwvf4akn2un7a5tsc4oq/node_modules/vite-auto-import-resolvers/dist/index.mjs:1:891 at file:///E:/Project/Vue3/xl-xling-admin/node_modules/.pnpm/[email protected]_v5xq3qlwvf4akn2un7a5tsc4oq/node_modules/vite-auto-import-resolvers/dist/index.mjs:2:61536 at file:///E:/Project/Vue3/xl-xling-admin/node_modules/.pnpm/[email protected]_v5xq3qlwvf4akn2un7a5tsc4oq/node_modules/vite-auto-import-resolvers/dist/index.mjs:1:891 at file:///E:/Project/Vue3/xl-xling-admin/node_modules/.pnpm/[email protected]_v5xq3qlwvf4akn2un7a5tsc4oq/node_modules/vite-auto-import-resolvers/dist/index.mjs:2:65541  ELIFECYCLE  Command failed with exit code 1.

autoimport url is not correct

It's my auto-imports.d.ts, I dont know why

// Generated by 'unplugin-auto-import'
// We suggest you to commit this file into source control
declare global {
// ....other....
const counterStore: typeof import('/Develop/workspace/小程序平台/mp-fw-ts/src/store/modules/counterStore')['default']
// ....other....
}

package.json

{
  "name": "vite-project",
  "private": true,
  "version": "0.0.0",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "@vueuse/core": "^8.2.5",
    "amfe-flexible": "^2.2.1",
    "mp-core-sdk": "^0.0.11",
    "normalize.css": "^8.0.1",
    "pinia": "^2.0.13",
    "vant": "^3.4.7",
    "vue": "^3.2.25",
    "vue-router": "^4.0.14"
  },
  "devDependencies": {
    "@types/node": "^17.0.23",
    "@typescript-eslint/eslint-plugin": "^5.1.0",
    "@typescript-eslint/parser": "^5.1.0",
    "@vitejs/plugin-vue": "^2.3.0",
    "@vitejs/plugin-vue-jsx": "^1.3.9",
    "consola": "^2.15.3",
    "eslint": "^7.2.0",
    "eslint-config-airbnb-base": "^14.2.1",
    "eslint-plugin-import": "^2.25.2",
    "eslint-plugin-typescript": "^0.14.0",
    "eslint-plugin-vue": "^7.20.0",
    "postcss": "^8.4.12",
    "postcss-pxtorem": "^6.0.0",
    "sass": "^1.50.0",
    "typescript": "^4.5.4",
    "unplugin-auto-import": "^0.7.0",
    "unplugin-vue-components": "^0.19.2",
    "vconsole": "^3.14.5",
    "vite": "^2.9.0",
    "vite-auto-import-resolvers": "^2.2.3",
    "vite-plugin-eslint": "^1.4.0",
    "vite-plugin-static-copy": "^0.4.4",
    "vite-plugin-style-import": "^2.0.0",
    "vite-plugin-vconsole": "^1.2.1",
    "vue-eslint-parser": "^7.11.0",
    "vue-tsc": "^0.29.8"
  }
}

vite.config.ts

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import { resolve } from 'path'
import { viteStaticCopy } from 'vite-plugin-static-copy'
import { createStyleImportPlugin, VantResolve } from 'vite-plugin-style-import'
import { viteVConsole } from 'vite-plugin-vconsole'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import {
  VantResolver,
  VueUseComponentsResolver,
} from 'unplugin-vue-components/resolvers'
import {
  dirResolver,
  DirResolverHelper,
} from 'vite-auto-import-resolvers'

// https://vitejs.dev/config/
export default defineConfig({
  server: {
    // 是否开启 https
    https: false,
    // 是否自动在浏览器打开
    open: false,
    // 端口号
    port: 8888,
    host: '0.0.0.0',
    proxy: {
      '/api': {
        // 后台接口
        target: '',
        changeOrigin: true,
        // 如果是https接口,需要配置这个参数
        secure: false,
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
    },
  },
  build: {
    outDir: 'dist',
  },
  plugins: [
    vue(),
    vueJsx(),
    createStyleImportPlugin({
      resolves: [VantResolve()],
    }),
    Components({
      dirs: ['src/components'],
      extensions: ['vue', 'tsx'],
      include: [/\.vue$/],
      dts: resolve(__dirname, './src/type/components.d.ts'),
      resolvers: [
        VantResolver(),
        VueUseComponentsResolver(),
      ],
    }),
    // 该辅助插件也是必需的 👇
    DirResolverHelper(),
    AutoImport(
      {
        dts: resolve(__dirname, './src/type/auto-imports.d.ts'),
        imports: [
          'vue',
          'pinia',
        ],
        resolvers: [
          dirResolver({
            target: 'store/modules',
            suffix: 'Store',
          }),
          VantResolver(),
        ],
      },
    ),
    viteVConsole({
      entry: resolve('src/main.ts'), // or you can use entry: [path.resolve('src/main.ts')]
      localEnabled: true,
      enabled: true,
      config: {
        maxLogNumber: 1000,
        theme: 'dark',
      },
    }),
    // copy 文件到dist目录 [1]表示只在build时启用
    viteStaticCopy({
      targets: [
        {
          src: 'src/manifest.json',
          dest: '',
        },
      ],
    })[1],
  ],
  resolve: {
    alias: {
      '@/': `${resolve(__dirname, 'src')}/`,
    },
  },
})

auto-imports.d.ts

// Generated by 'unplugin-auto-import'
// We suggest you to commit this file into source control
declare global {
  const acceptHMRUpdate: typeof import('pinia')['acceptHMRUpdate']
  const computed: typeof import('vue')['computed']
  const counterStore: typeof import('/Develop/workspace/小程序平台/mp-fw-ts/src/store/modules/counterStore')['default']
  const createApp: typeof import('vue')['createApp']
  const createPinia: typeof import('pinia')['createPinia']
  const customRef: typeof import('vue')['customRef']
  const defineAsyncComponent: typeof import('vue')['defineAsyncComponent']
  const defineComponent: typeof import('vue')['defineComponent']
  const defineStore: typeof import('pinia')['defineStore']
  const effectScope: typeof import('vue')['effectScope']
  const EffectScope: typeof import('vue')['EffectScope']
  const getActivePinia: typeof import('pinia')['getActivePinia']
  const getCurrentInstance: typeof import('vue')['getCurrentInstance']
  const getCurrentScope: typeof import('vue')['getCurrentScope']
  const h: typeof import('vue')['h']
  const inject: typeof import('vue')['inject']
  const isReadonly: typeof import('vue')['isReadonly']
  const isRef: typeof import('vue')['isRef']
  const mapActions: typeof import('pinia')['mapActions']
  const mapGetters: typeof import('pinia')['mapGetters']
  const mapState: typeof import('pinia')['mapState']
  const mapStores: typeof import('pinia')['mapStores']
  const mapWritableState: typeof import('pinia')['mapWritableState']
  const markRaw: typeof import('vue')['markRaw']
  const nextTick: typeof import('vue')['nextTick']
  const onActivated: typeof import('vue')['onActivated']
  const onBeforeMount: typeof import('vue')['onBeforeMount']
  const onBeforeUnmount: typeof import('vue')['onBeforeUnmount']
  const onBeforeUpdate: typeof import('vue')['onBeforeUpdate']
  const onDeactivated: typeof import('vue')['onDeactivated']
  const onErrorCaptured: typeof import('vue')['onErrorCaptured']
  const onMounted: typeof import('vue')['onMounted']
  const onRenderTracked: typeof import('vue')['onRenderTracked']
  const onRenderTriggered: typeof import('vue')['onRenderTriggered']
  const onScopeDispose: typeof import('vue')['onScopeDispose']
  const onServerPrefetch: typeof import('vue')['onServerPrefetch']
  const onUnmounted: typeof import('vue')['onUnmounted']
  const onUpdated: typeof import('vue')['onUpdated']
  const provide: typeof import('vue')['provide']
  const reactive: typeof import('vue')['reactive']
  const readonly: typeof import('vue')['readonly']
  const ref: typeof import('vue')['ref']
  const resolveComponent: typeof import('vue')['resolveComponent']
  const setActivePinia: typeof import('pinia')['setActivePinia']
  const setMapStoreSuffix: typeof import('pinia')['setMapStoreSuffix']
  const shallowReactive: typeof import('vue')['shallowReactive']
  const shallowReadonly: typeof import('vue')['shallowReadonly']
  const shallowRef: typeof import('vue')['shallowRef']
  const storeToRefs: typeof import('pinia')['storeToRefs']
  const toRaw: typeof import('vue')['toRaw']
  const toRef: typeof import('vue')['toRef']
  const toRefs: typeof import('vue')['toRefs']
  const triggerRef: typeof import('vue')['triggerRef']
  const unref: typeof import('vue')['unref']
  const useAttrs: typeof import('vue')['useAttrs']
  const useCssModule: typeof import('vue')['useCssModule']
  const useCssVars: typeof import('vue')['useCssVars']
  const useSlots: typeof import('vue')['useSlots']
  const watch: typeof import('vue')['watch']
  const watchEffect: typeof import('vue')['watchEffect']
}
export {}

Scan non `default` exports

Currently there is option to auto import composable that are only exported as default export

// src/composable/useFoo.ts

export default 1000

export const bar = 500

bar won't be able to be avaiable for autoimport, Yes I can add ne composable, but in some cases it would be better to have in same file cause they in same context, and its better for tree-shaking.

Food for thought.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.