Git Product home page Git Product logo

unplugin-auto-import's Introduction

unplugin-auto-import

NPM version

Auto import APIs on-demand for Vite, Webpack, Rspack, Rollup and esbuild. With TypeScript support. Powered by unplugin.


without

import { computed, ref } from 'vue'

const count = ref(0)
const doubled = computed(() => count.value * 2)

with

const count = ref(0)
const doubled = computed(() => count.value * 2)

without

import { useState } from 'react'

export function Counter() {
  const [count, setCount] = useState(0)
  return <div>{ count }</div>
}

with

export function Counter() {
  const [count, setCount] = useState(0)
  return <div>{ count }</div>
}

Install

npm i -D unplugin-auto-import
Vite
// vite.config.ts
import AutoImport from 'unplugin-auto-import/vite'

export default defineConfig({
  plugins: [
    AutoImport({ /* options */ }),
  ],
})

Example: playground/


Rollup
// rollup.config.js
import AutoImport from 'unplugin-auto-import/rollup'

export default {
  plugins: [
    AutoImport({ /* options */ }),
    // other plugins
  ],
}


Webpack
// webpack.config.js
module.exports = {
  /* ... */
  plugins: [
    require('unplugin-auto-import/webpack').default({ /* options */ }),
  ],
}


Rspack
// rspack.config.js
module.exports = {
  /* ... */
  plugins: [
    require('unplugin-auto-import/rspack').default({ /* options */ }),
  ],
}


Nuxt

You don't need this plugin for Nuxt, it's already builtin.


Vue CLI
// vue.config.js
module.exports = {
  /* ... */
  plugins: [
    require('unplugin-auto-import/webpack').default({ /* options */ }),
  ],
}

You can also rename the Vue configuration file to vue.config.mjs and use static import syntax (you should use latest @vue/cli-service ^5.0.8):

// vue.config.mjs
import AutoImport from 'unplugin-auto-import/webpack'

export default {
  configureWebpack: {
    plugins: [
      AutoImport({ /* options */ }),
    ],
  },
}


Quasar
// vite.config.js [Vite]
import { defineConfig } from 'vite'
import AutoImport from 'unplugin-auto-import/vite'

export default defineConfig({
  plugins: [
    AutoImport({ /* options */ })
  ]
})
// quasar.conf.js [Webpack]
const AutoImportPlugin = require('unplugin-auto-import/webpack').default

module.exports = {
  build: {
    chainWebpack(chain) {
      chain.plugin('unplugin-auto-import').use(
        AutoImportPlugin({ /* options */ }),
      )
    },
  },
}


esbuild
// esbuild.config.js
import { build } from 'esbuild'
import AutoImport from 'unplugin-auto-import/esbuild'

build({
  /* ... */
  plugins: [
    AutoImport({
      /* options */
    }),
  ],
})


Astro
// astro.config.mjs
import AutoImport from 'unplugin-auto-import/astro'

export default defineConfig({
  integrations: [
    AutoImport({
      /* options */
    })
  ],
})


Configuration

AutoImport({
  // targets to transform
  include: [
    /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
    /\.vue$/,
    /\.vue\?vue/, // .vue
    /\.md$/, // .md
  ],

  // global imports to register
  imports: [
    // presets
    'vue',
    'vue-router',
    // custom
    {
      '@vueuse/core': [
        // named imports
        'useMouse', // import { useMouse } from '@vueuse/core',
        // alias
        ['useFetch', 'useMyFetch'], // import { useFetch as useMyFetch } from '@vueuse/core',
      ],
      'axios': [
        // default imports
        ['default', 'axios'], // import { default as axios } from 'axios',
      ],
      '[package-name]': [
        '[import-names]',
        // alias
        ['[from]', '[alias]'],
      ],
    },
    // example type import
    {
      from: 'vue-router',
      imports: ['RouteLocationRaw'],
      type: true,
    },
  ],

  // Array of strings of regexes that contains imports meant to be filtered out.
  ignore: [
    'useMouse',
    'useFetch'
  ],

  // Enable auto import by filename for default module exports under directories
  defaultExportByFilename: false,

  // Auto import for module exports under directories
  // by default it only scan one level of modules under the directory
  dirs: [
    // './hooks',
    // './composables' // only root modules
    // './composables/**', // all nested modules
    // ...
  ],

  // Filepath to generate corresponding .d.ts file.
  // Defaults to './auto-imports.d.ts' when `typescript` is installed locally.
  // Set `false` to disable.
  dts: './auto-imports.d.ts',

  // Array of strings of regexes that contains imports meant to be ignored during
  // the declaration file generation. You may find this useful when you need to provide
  // a custom signature for a function.
  ignoreDts: [
    'ignoredFunction',
    /^ignore_/
  ],

  // Auto import inside Vue template
  // see https://github.com/unjs/unimport/pull/15 and https://github.com/unjs/unimport/pull/72
  vueTemplate: false,

  // Custom resolvers, compatible with `unplugin-vue-components`
  // see https://github.com/antfu/unplugin-auto-import/pull/23/
  resolvers: [
    /* ... */
  ],

  // Inject the imports at the end of other imports
  injectAtEnd: true,

  // Generate corresponding .eslintrc-auto-import.json file.
  // eslint globals Docs - https://eslint.org/docs/user-guide/configuring/language-options#specifying-globals
  eslintrc: {
    enabled: false, // Default `false`
    // provide path ending with `.mjs` or `.cjs` to generate the file with the respective format
    filepath: './.eslintrc-auto-import.json', // Default `./.eslintrc-auto-import.json`
    globalsPropValue: true, // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
  },
})

Refer to the type definitions for more options.

Presets

See src/presets.

Package Presets

We only provide presets for the most popular packages, to use any package not included here you can install it as dev dependency and add it to the packagePresets array option:

AutoImport({
  /* other options */
  packagePresets: ['detect-browser-es'/* other local package names */]
})

You can check the Svelte example for a working example registering detect-browser-es package preset and auto importing detect function in App.svelte.

Please refer to the unimport PackagePresets jsdocs for more information about options like ignore or cache.

Note: ensure local packages used have package exports configured properly, otherwise the corresponding modules exports will not be detected.

TypeScript

In order to properly hint types for auto-imported APIs

  1. Enable options.dts so that auto-imports.d.ts file is automatically generated
  2. Make sure auto-imports.d.ts is not excluded in tsconfig.json

AutoImport({
  dts: true // or a custom path
})

ESLint

💡 When using TypeScript, we recommend to disable no-undef rule directly as TypeScript already check for them and you don't need to worry about this.

If you have encountered ESLint error of no-undef:

  1. Enable eslintrc.enabled

AutoImport({
  eslintrc: {
    enabled: true, // <-- this
  },
})
  1. Update your eslintrc: Extending Configuration Files

// .eslintrc.js
module.exports = {
  extends: [
    './.eslintrc-auto-import.json',
  ],
}

FAQ

Compare to unimport

From v0.8.0, unplugin-auto-import uses unimport underneath. unimport is designed to be a lower-level tool (it also powered Nuxt's auto import). You can think unplugin-auto-import is a wrapper of it that provides more user-friendly config APIs and capabilities like resolvers. Development of new features will mostly happen in unimport from now.

Compare to vue-global-api

You can think of this plugin as a successor to vue-global-api, but offering much more flexibility and bindings with libraries other than Vue (e.g. React).

Pros
  • Flexible and customizable
  • Tree-shakable (on-demand transforming)
  • No global population
Cons
  • Relying on build tools integrations (while vue-global-api is pure runtime) - but hey, we have supported quite a few of them already!

Sponsors

License

MIT License © 2021-PRESENT Anthony Fu

unplugin-auto-import's People

Contributors

antfu avatar ascott18 avatar azaleta avatar dammy001 avatar davay42 avatar ddosakura avatar demivan avatar jiagang avatar jounqin avatar jungzl avatar lishaobos avatar lxy-yz avatar markthree avatar menghany avatar minenwerfer avatar oumarbarry avatar peerless-hero avatar samuveth avatar seahindeniz avatar sibbng avatar simeonkerkola avatar soya-xy avatar sxzz avatar tdolsen avatar thedelk avatar tmkx avatar userquin avatar walkalone0325 avatar weilence avatar wobsoriano 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

unplugin-auto-import's Issues

require("unplugin-auto-import/webpack") is not a function

plugin doesnt works in vue-cli ~4.5.0 + vue ^2.6.11, project is generated by vue-cli's template

require("unplugin-vue2-script-setup/webpack")({
  // everything is ok
}),
require("unplugin-auto-import/webpack")({
  // v0.4.8 throw error, v0.2.7 is ok 
})

Calling itself inside a recursive function will cause a circular reference

  • The code is like this, it works well at ^0.2.7
export const deepClone = (obj: any) => {
  if ([null, undefined, NaN, false].includes(obj)) {
    return obj;
  }
  if (typeof obj !== 'object') {
    return obj;
  }
  const temp:any = isArray(obj) ? [] : {};
  for (const key in obj) {
    if ([Date, RegExp, Function].some((_type) => obj[key] instanceof _type)) {
      temp[key] = obj[key];
      continue;
    }
    if (obj.hasOwnProperty(key)) {
      temp[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key];
    }
  }
  return temp;
};
  • But after ^0.2.7 and until now(^0.4.0), it will import itself in where it is defined

2021-09-03_16-01

Can't pass type-checking with vue-tsc

using https://github.com/antfu/vitesse as example.

src/pages/[...all].vue:2:15 - error TS2304: Cannot find name 'useI18n'.

2 const { t } = useI18n()
~~~~~~~

src/layouts/404.vue:2:16 - error TS2304: Cannot find name 'useRouter'.

2 const router = useRouter()
~~~~~~~~~

src/layouts/404.vue:3:15 - error TS2304: Cannot find name 'useI18n'.

3 const { t } = useI18n()
~~~~~~~

src/pages/index.vue:5:14 - error TS2304: Cannot find name 'ref'.

5 const name = ref(user.savedName)

image

missing echarts import

version: 0.3.3 & 0.4.0

config:

        {
          'echarts/core': ['use', 'graphic'],
          'echarts/renderers': ['CanvasRenderer'],
          'echarts/charts': [
            'BarChart',
            'PieChart',
            'LineChart',
            'RadarChart',
            'GaugeChart',
          ],
          'echarts/components': [
            'DatasetComponent',
            'DataZoomComponent',
            'GridComponent',
            'LegendComponent',
            'MarkLineComponent',
            'TitleComponent',
            'ToolboxComponent',
            'TooltipComponent',
          ],
        }

error:

Uncaught ReferenceError: LegendComponent is not defined

This problem does not exist in version 0.2.7

Axios import?

Any way to add axios to this?

I tried this in the imports config , but it didn't work:

 imports: [
        'vue',
        'vue-router',
        '@vueuse/head',
        '@vueuse/core',
        {
          'axios': ['axios']
        }
      ]

npm i -D unplugin-auto-import ERROR on quasar project (not Vite)

I'm getting thew following error after creating a new quasar project with

quasar create quasar-sandbox

Am i doing something wrong?

npm i -D unplugin-auto-import gives the following error

npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR! 
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/vue
npm ERR!   vue@"3.2.20" from @quasar/[email protected]
npm ERR!   node_modules/@quasar/app
npm ERR!     dev @quasar/app@"^3.0.0" from the root project
npm ERR!   peer vue@"3.2.20" from @vue/[email protected]
npm ERR!   node_modules/@vue/server-renderer
npm ERR!     @vue/server-renderer@"3.2.20" from [email protected]
npm ERR!   3 more (vue-i18n, vue-router, vuex)
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! dev unplugin-auto-import@"*" from the root project
npm ERR! 
npm ERR! Conflicting peer dependency: [email protected]
npm ERR! node_modules/vue
npm ERR!   peer vue@">= 2.5 < 3" from @vue/[email protected]
npm ERR!   node_modules/@vue/composition-api
npm ERR!     peerOptional @vue/composition-api@"^1.1.0" from @vueuse/[email protected]
npm ERR!     node_modules/@vueuse/core
npm ERR!       peerOptional @vueuse/core@"^6.0.0" from [email protected]
npm ERR!       node_modules/unplugin-auto-import
npm ERR!         dev unplugin-auto-import@"*" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR! 
npm ERR! See /Users/imp_r.molloy/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/imp_r.molloy/.npm/_logs/2021-10-31T19_28_30_197Z-debug.log

add vuex presets

I'm sorry that I don't have time to submit a pull request. This should be trivial for anyone with a dev environment already set up.
All that is needed is to copy vue-router preset and change from the vue-router words in the table below.

vue-router vuex
vue-router vuex
useRoute useStore

This would uniformly support the composition api for these common libraries.

In addition the presets readme has "do some rules" which should be "do have some rules".

Plans to support ESLint

Great job as always @antfu

Do you have any plans to support ESLint config? e.g. generating auto-imports-eslintrc.js we can just include into extend section of .eslintrc.js ?

Types not working with Nuxt

Originally posted by @wobsoriano in antfu/vue-global-api#20 (comment)

buildModules: [
  '@nuxt/typescript-build',
  '@nuxtjs/composition-api/module',
  'nuxt-typed-vuex',
  [
    'unplugin-auto-import/nuxt',
    {
      // global imports to register
      // imports: ['vue2']
      imports: [
        {
          '@nuxtjs/composition-api': CommonCompositionAPI,
        },
      ],
    },
  ],
],

Preset vue2 and custom preset still gives cannot find name 'defineComponent' etc..

Screen Shot 2021-08-24 at 6 12 21 PM

Also tried restarting vs code with no luck

Nuxt type error The 'request' argument must be string

image

I am using nuxt version 2.14.7

after added below, above error occered

 buildModules: [
    '@nuxtjs/composition-api/module',
    { include: [/\.[tj]sx?$/, /\.vue\??/] }
  ]

Is there somethind more I have to do to use this module? I have no idea with this error

 FATAL  The 'request' argument must be string. Received type undefined

  at node_modules/esm/esm.js:1:224803
  at Module.<anonymous> (node_modules/esm/esm.js:1:295892)
  at Resolver.n [as _require] (node_modules/esm/esm.js:1:279589)
  at Resolver.requireModule (node_modules/@nuxt/core/dist/core.js:615:31)
  at ModuleContainer.addModule (node_modules/@nuxt/core/dist/core.js:180:38)
  at node_modules/@nuxt/utils/dist/utils.js:1846:43
  at async ModuleContainer.ready (node_modules/@nuxt/core/dist/core.js:51:7)
  at async Nuxt._init (node_modules/@nuxt/core/dist/core.js:715:5)


   ╭────────────────────────────────────────────────────────────────╮
   │                                                                │
   │   ✖ Nuxt Fatal Error                                           │
   │                                                                │
   │   TypeError: The 'request' argument must be string. Received   │
   │   type undefined                                               │
   │                                                                │
   ╰────────────────────────────────────────────────────────────────╯

[nodemon] app crashed - waiting for file changes before starting...

Bundle size increases with the plugin when used in a quasar project

Hii @antfu, When a normal build is done on a quasar project, the build bundle size is 500kb smaller than a build with the plugin used.

Steps to reproduce

  • create a new quasar cli project
  • do a normal build
  • check dist/spa folder size
  • install unplugin-auto-import
  • add it in quasar config with the following presets installed
 chainWebpack(chain) {
        chain.plugin('unplugin-auto-import').use(
          AutoImportPlugin({
            // targets to transform
            include: [
              /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
              /\.vue$/,
              /\.vue\?vue/, // .vue
              /\.md$/, // .md
            ],

            // global imports to register
            imports: [
              // presets
              'vue',
              'vue-router',
              'vuex',
              'quasar',
            ],
          })
        );
      },
  • remove all vue API imports and run a build
  • check dist/spa folder size
  • it's higher than that of the normal build

What's expected

  • The bundle size should remain the same because we have Tree shaking in place

What happenes

  • The bundle size with the plugin is larger than without the plugin

Please let me know if you need a repo to reproduce. I did it with a project with around 20 .vue files and 10 plus .ts files

How to use with Jest ?

version: 0.4.5

// MyComponent.tsx
export default defineComponent({
    // ....
})

// *.spec.ts
it('should render', () => {
    const wrapper = shallowMount(MyComponent)  // throw error: defineComponent is not defined
})

Needs better doc for custom imports.

In the readme for configuration the custom section is shown as

// custom
    {
      '@vueuse/core': [
        'useMouse'
      ],
      '[package-name]': [
        '[import-names]',
        // alias
        ['[from]', '[alias]']
      ]
    }

I'm not sure if

 '@vueuse/core': [
        'useMouse'
      ],

is an example or actually provides useMouse
I assumed that it was working code and added my own section

'vuex': ['useStore']

and it did not work to import useStore into my vue components.

In addition, the rest of the custom section looks like a template and not actual code, but with no explanation I can't tell.

False positive detection in comments

Hello!

I gave a try with vitesse template and a standalone vite project, everything seams to work quite well.. except when I'm not using typescript (eg. no "lang='ts'" and/or no tsconfig.json).

Maybe this library is designed to work especially with TS? But the samples in the readme do not include any TS (except vite config example) ; while playground and nuxt example do.

I'm using vite, vue 3 and <script setup> format.

项目名中含有特殊符号

项目名中存在特殊符号,发现无法自动导入,运行起来出现 ReferenceError: *** is not defined。虽然修改文件夹名称就可以,但还请兼容下,谢谢🙏。

image

image

Error: [auto-import] failed to load @vueuse/core, have you installed it?

[20:19:40] failed to load config from /root/workspace/wenzuo5_wenzuo-auth-fe_nfgy/vite.config.ts
[20:19:40] error during build:
[20:19:40] Error: [auto-import] failed to load @vueuse/core, have you installed it?
[20:19:40]     at vueuse_core_default (/root/workspace/wenzuo5_wenzuo-auth-fe_nfgy/node_modules/[email protected]@unplugin-auto-import/dist/chunk-T5OU4655.js:227:13)
[20:19:40]     at /root/workspace/wenzuo5_wenzuo-auth-fe_nfgy/node_modules/[email protected]@unplugin-auto-import/dist/chunk-5I5CMYBW.js:39:51
[20:19:40]     at Array.forEach (<anonymous>)
[20:19:40]     at flattenImportsMap (/root/workspace/wenzuo5_wenzuo-auth-fe_nfgy/node_modules/[email protected]@unplugin-auto-import/dist/chunk-5I5CMYBW.js:34:36)
[20:19:40]     at resolveOptions (/root/workspace/wenzuo5_wenzuo-auth-fe_nfgy/node_modules/[email protected]@unplugin-auto-import/dist/chunk-5I5CMYBW.js:18:19)
[20:19:40]     at /root/workspace/wenzuo5_wenzuo-auth-fe_nfgy/node_modules/[email protected]@unplugin-auto-import/dist/chunk-5I5CMYBW.js:159:20
[20:19:40]     at /root/workspace/wenzuo5_wenzuo-auth-fe_nfgy/node_modules/[email protected]@unplugin/dist/index.js:79:23
[20:19:40]     at Object.<anonymous> (/root/workspace/wenzuo5_wenzuo-auth-fe_nfgy/vite.config.ts:43:28)
[20:19:40]     at Module._compile (internal/modules/cjs/loader.js:1251:30)
[20:19:40]     at Object.require.extensions.<computed> [as .ts] (/root/workspace/wenzuo5_wenzuo-auth-fe_nfgy/node_modules/[email protected]@vite/dist/node/chunks/dep-1be34a63.js:77161:20)
[20:19:40] npm info lifecycle [email protected]~build: Failed to exec build script
[20:19:40] npm ERR! code ELIFECYCLE
[20:19:40] npm ERR! errno 1
[20:19:40] npm ERR! [email protected] build: `vue-tsc --noEmit && vite build`
[20:19:40] npm ERR! Exit status 1
[20:19:40] npm ERR! 
[20:19:40] npm ERR! Failed at the [email protected] build script.
[20:19:40] npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
[20:19:40] npm timing npm Completed in 9112ms
[20:19:40] 
[20:19:40] npm ERR! A complete log of this run can be found in:

this is my config

  // https://github.com/antfu/unplugin-auto-import
  AutoImport({
    imports: [
      'vue',
      'vue-router',
      '@vueuse/core',
      '@vueuse/head'
    ],
    dts: true,
  }),

Not issue but a question

I have in my code something like this :

import { dsLoadData, dsGetData } from '@/bootstrap/4p2p/utils/p-api'

Its possible to include this in custom resolvers ( vite.config.js -> AutoImport )

Thanks

Pedro Martins

RFC: Auto register for types

Context:

For example, it would be great to have common types like Ref, ComputedRef globally available when using the Vue preset. I would expect the API to be like

{
  // auto importing for import
  imports: [
    'vue'
  ],
  // auto importing for types
  types: [
    'vue', // again, we could have presets for it.
    {
      vue: ['Ref', 'ComputedRef']
    }
  ]
}

docs: update configuration to use correct `include` option for `vue` and `md`

REMINDER

The entry for vue configuration should be include: [/\.vue$/, /\.vue\?vue/].

Also add using mardown, for example when using vitepress or vite-plugin-md: include: [/\.vue$/, /\.vue\?vue/, /\.md$/].

Configuration entry on readme should be something like this:

AutoImport({
  // targets to transform
  include: [
    /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
    /\.vue$/, /\.vue\?vue/, // .vue
    /\.md$/, // .md
  ],
  ...
})

onDeactivated not defined

Everything is working except for
onDeactivated

throwing
ReferenceError
onDeactivated is not defined

    ['unplugin-auto-import/nuxt', { imports: ['@nuxtjs/composition-api'] }],

It is also missing in auto-imports.d.ts

Thank you

Terminal logs out large amount of infos After switching to unplugin-auto-import from vue-global-api

Sourcemap for "/Users/han/Dev/fb-desktop-ssr/components/fb-chat/components/module-content/src/list-item.vue" points to missing source files
Sourcemap for "/Users/han/Dev/fb-desktop-ssr/components/fb-chat/components/module-content/src/detail/book-volumn-docs/doc-list.vue" points to missing source files
Sourcemap for "/Users/han/Dev/fb-desktop-ssr/pages/agreement/components/commonAside.vue" points to missing source files
Sourcemap for "/Users/han/Dev/fb-desktop-ssr/pages/agreement/components/commonHead.vue" points to missing source files
Sourcemap for "/Users/han/Dev/fb-desktop-ssr/components/fb-cropper/index.vue" points to missing source files
Sourcemap for "/Users/han/Dev/fb-desktop-ssr/pages/search/components/list/sort-item.vue" points to missing source files
Sourcemap for "/Users/han/Dev/fb-desktop-ssr/pages/search/components/skeletonItem.vue" points to missing source files
Sourcemap for "/Users/han/Dev/fb-desktop-ssr/pages/search/components/list/common-filter.vue" points to missing source files
Sourcemap for "/Users/han/Dev/fb-desktop-ssr/pages/search/components/list/batch-download.vue" points to missing source files
Sourcemap for "/Users/han/Dev/fb-desktop-ssr/components/fb-chat/components/module-content/src/type-tag.vue" points to missing source files
Sourcemap for "/Users/han/Dev/fb-desktop-ssr/pages/search/components/list/search-result.vue" points to missing source files
Sourcemap for "/Users/han/Dev/fb-desktop-ssr/pages/search/components/list/judgement-list-item.vue" points to missing source files
Sourcemap for "/Users/han/Dev/fb-desktop-ssr/pages/search/components/list/number-checkbox.vue" points to missing source files
...and much more

Is it releated to unplugin-auto-import or unplugin-vue2-script-setup?
I am not quite sure what all these logs means but I know these components are vue2 legacy version(by Options API and without TS definition or defineComponent).

Thanks for reply.

Plugin is breaking when Glob Import is used

In a project with Vue, when utilizing Glob Import, any reference to Vue's export
after the statement import.meta.glob throws an error.

The following example throws an error at runtime.
ReferenceError: ref is not defined.

<script setup>
const modules = import.meta.glob('/src/nested/*.vue')
const value = ref('hello')
</script>

However, this works:

<script setup>
const value = ref('hello')
const modules = import.meta.glob('/src/nested/*.vue')
</script>

vite.config.js

import { defineConfig } from 'vite'
import Vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'

export default defineConfig({
  plugins: [
    Vue(),
    AutoImport({
      imports: [ 'vue' ],
    }),
  ],
})

I am able to replicate the issue with minimal setup.
https://codesandbox.io/s/vite-project-forked-frnfh?file=/src/App-breaking.vue

Make it clear that it doesn't need <script setup> to work

I've noticed some misunderstandings in the community that unplugin-auto-import requires using <script setup> syntax, based on the fact that the code examples are using it exclusively.
It could possibly be helpful to state that it's not necessary and it works just fine without it.

add quasar config example to doc

The quasar framework is built on top of Vue. Using the Vue imports would be very useful in quasar. But Quasar has its own config file and does webpack configuration a little differently than Vue cli. An example for quasar would extend the ease of use to one more platform.

alias doesnt work as expected in vue-cli

when i try this

imports: [
    { 
        'vue-types': [ 
            ['default', 'VueTypes'], 
            // others...
        ] 
    }
]

the error is:

Module parse failed: Identifier 'VueTypes' has already been declared.

import { default as VueTypes } from 'vue-types';import { object, default as VueTypes } from 'vue-types';

Recommended way to use both vue and nuxt composition api presets

@nuxtjs/composition-api preset is good but when I try to load also @vue/composition-api preset to get TS interfaces, I end up with ERROR [auto-import] identifier onActivated already defined with @vue/composition-api.

What's the recommended solution for using two presets that partly overwrite each other? Should I add missing stuff individually as an array?

项目名中含有特殊符号

项目名中存在特殊符号,发现无法自动导入,运行起来出现 ReferenceError: *** is not defined。修改文件夹名称就可以,如果可以的话还是请兼容下🙏。

image

image

Any chance to replace `vite-plugin-components` too?

vite-plugin-icons and compents auto import are now depends on vite-plugin-components, and generate types in components.d.ts.

While unplugin-auto-import in auto-imports.d.ts.

is there any chance to combine vite-plugin-components in unplugin-auto-import?

Doesn't work with dollar sign `$`

I tried vue and v-dollar, both of them didn't work.

AutoImport({
    dts: './src/auto-imports.d.ts',
    imports: [
      'vue',
      {
        'vue': [
          ['unref', '$'],
        ],
      },
    ],
  }),
AutoImport({
    dts: './src/auto-imports.d.ts',
    imports: [
      'vue',
      {
        'v-dollar': [
          '$',
        ],
      },
    ],
  }),

I have "cannot find module" error when running the project

When I run npm run dev

Captura de Pantalla 2021-08-24 a la(s) 08 38 58

//vite.config.ts

import { defineConfig } from "vite";
import Vue from "@vitejs/plugin-vue";
import WindiCSS from "vite-plugin-windicss";
import Pages from "vite-plugin-pages";
import ViteIcons, { ViteIconsResolver } from "vite-plugin-icons";
import ViteComponents from "vite-plugin-components";
import { VitePWA } from "vite-plugin-pwa";
import AutoImport from "unplugin-auto-import/vite";

export default defineConfig({
  plugins: [
    Vue(),
    Pages({ nuxtStyle: false }),
    ViteComponents({
      directoryAsNamespace: true,
      customComponentResolvers: ViteIconsResolver({
        componentPrefix: "icon",
      }),
    }),
    VitePWA(),
    WindiCSS({
      transformCSS: "pre",
      preflight: true,
    }),
    ViteIcons(),
    AutoImport({ imports: "vue" }),
  ],
});

Dev is fine, but has build errors as well as IDE warnings

Thanks for this helper tool. I have tried to use it in place of vue-global-api.

Dev runs OK, but fails to build. Also, the VSCode+Volar IDE complains "cannot find name xxx"

My vite.config.ts:

import { defineConfig } from 'vite'
import Vue from '@vitejs/plugin-vue'
import Pages from 'vite-plugin-pages'
import ViteComponents from 'vite-plugin-components'
import WindiCSS from 'vite-plugin-windicss'
import AutoImport from 'unplugin-auto-import/vite'
import { join } from 'path'
const fs = require('fs')

export default defineConfig({
  base: '/paperless/',
  resolve: {
    alias: {
      '@': join(__dirname, 'src'),
      '~': join(__dirname, 'src')
    }
  },
  server: {
    https: {
      key: fs.readFileSync('localhost+5-key.pem'),
      cert: fs.readFileSync('localhost+5.pem')
    },
    fs: {
      // Allow serving files from one level up to the project root
      allow: ['..']
    }
  },
  plugins: [
    Vue(),
    AutoImport({
      imports: 'vue'
    }),
    Pages(),
    ViteComponents({
      globalComponentsDeclaration: true
    }),
    WindiCSS({
      transformCSS: 'pre',
      preflight: true
    })
  ],
  optimizeDeps: {
    include: ['vue', 'vue-router', '@vueuse/core']
  }
})
> vue-tsc --noEmit && vite build

src/layouts/main.vue:10:3 - error TS2304: Cannot find name 'onMounted'.

10   onMounted(() => {
     ~~~~~~~~~

src/App.vue:14:18 - error TS2304: Cannot find name 'computed'.

14   const layout = computed(() => {
                    ~~~~~~~~

src/components/a-name-status.vue:18:17 - error TS2304: Cannot find name 'computed'.

18   const color = computed(() => {
                   ~~~~~~~~

src/pages/exchange-rates.vue:21:33 - error TS2345: Argument of type 'string | number | symbol' is not assignable to parameter of type 'number'.
  Type 'string' is not assignable to type 'number'.

21                 @click="view(o, i)"
                                   ~

src/components/a-name-status.vue:29:17 - error TS2304: Cannot find name 'computed'.

29   const label = computed(() => {
                   ~~~~~~~~

src/pages/salaries.vue:22:36 - error TS2365: Operator '+' cannot be applied to types 'string | number | symbol' and 'number'.

......

[vite] Internal server error: Failed to resolve import "primevue/tooltip/Tooltip.vue"

I follow the installation of tooltip of PrimeVue https://primefaces.org/primevue/showcase/#/tooltip

It shows this error below when I use v-tooltip="'Click to proceed'" on an element.

[vite] Internal server error: Failed to resolve import "primevue/tooltip/Tooltip.vue" from "src\App.vue". Does the file exist?

dependencies version:

"primevue": "^3.8.2",
"unplugin-auto-import": "^0.4.13",
"vite": "^2.6.12",

I hava another project that use PrimeVue tooltip and it's working fine. I tried downgrade the current project's dependencies version to be the same as the working one and also tried delete node_modules and run npm i again, but no luck.

"primevue": "^3.8.0",
"unplugin-auto-import": "^0.4.12",
"vite": "^2.6.7",

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.