Unified utils for auto importing APIs in modules.

Related tags

Vue.js webpack vite
Overview

unimport

npm version npm downloads Github Actions Codecov

Unified utils for auto importing APIs in modules

Install

# npm
npm install unimport

# yarn
yarn install unimport

# pnpm
pnpm install unimport

Usage

Plugin Usage

Powered by unplugin, unimport provides a plugin interface for bundlers.

Vite / Rollup

// vite.config.js / rollup.config.js
import Unimport from 'unimport/unplugin'

export default {
  plugins: [
    Unimport.vite({ /* plugin options */ })
  ]
}

Webpack

// webpack.config.js
import Unimport from 'unimport/unplugin'

module.exports = {
  plugins: [
    Unimport.webpack({ /* plugin options */ })
  ]
}

Programmatic Usage

// ESM
import { createUnimport } from 'unimport'

// CommonJS
const { createUnimport } = require('unimport')
const { injectImports } = createUnimport({
  imports: [{ name: 'fooBar', from: 'test-id' }]
})

// { code: "import { fooBar } from 'test-id';console.log(fooBar())" }
console.log(injectImports('console.log(fooBar())'))

💻 Development

  • Clone this repository
  • Enable Corepack using corepack enable (use npm i -g corepack for Node.js < 16.10)
  • Install dependencies using yarn install
  • Run interactive tests using yarn dev

License

Made with 💛

Published under MIT License.

Comments
  • Including merging with an existing import declaration

    Including merging with an existing import declaration

    Filing a separate issue out of #1 to help me keep track. 😄

    @pi0 this looks like it'd be a good first contribution for me - if you don't mind, I'd like to tackle it soon.

    opened by JoshuaKGoldberg 6
  • fix: vue template ComponentCustomProperties interface

    fix: vue template ComponentCustomProperties interface

    Fix https://github.com/antfu/unplugin-auto-import/issues/263.

    Currently will occur type errors when ComponentCustomProperties under @vue/runtime-core, I think we should follow the Vue documentation to define it.

    opened by qmhc 3
  • fix: manual update map when changing dynamicImport

    fix: manual update map when changing dynamicImport

    Fixed ctx.map not updating if ctx.map was accessed directly after calling modifyDynamicImports without calling the getter of ctx.imports.

    Normal projects will probably not encounter this problem because they have a lot of files, but I happened to build a minimalist project with basically only two files to verify the function of this library, and it didn't work.

    You can modify the files in the playground folder like this to reproduce:

    // playground/src/main.ts
    console.log(foo())
    
    // playground/vite.config.ts
    export default defineConfig({
      plugins: [
        vue(),
        unimport.vite({
          // dts: true,
          presets: [
            'vue'
          ],
          dirs: [
            './composables'
          ],
          addons: {
            vueTemplate: true
          }
        }),
        // inspect()
      ]
    })
    

    It's a bad idea to have side effects in getters, if you uncomment dts: true or inspect() the plugin will work again.

    opened by vhhsyt 3
  • fix: use `strip-literal` for more correct comments removal

    fix: use `strip-literal` for more correct comments removal

    When applying unimport on huge codebase, I've encountered many issues when global identifiers were not detected. Some of them were fixed in #58 , but after that fix I've found several more complicated cases, e.g.:

    const url = `http://${ref()}`
    

    "//" was detected as single-line comment, discarded rest of the line, and first "`" quote was left unclosed, which lead to discarding of entire code.

    This is complex to fix via replacing regexes, because many combinations are possible depending on the order - `str` // comment vs `str // not comment`.

    To fix it properly we probably need to parse the syntax tree, but if I understood correctly Vite doesn't want to do it for performance reasons. So I've written small "state machine" to correctly detect strings and comments regardless of nesting in in O(n) time.

    opened by leo-buneev 3
  • `scanDirs` is not respecting the priority order of auto-imports

    `scanDirs` is not respecting the priority order of auto-imports

    I am wondering why the current implementation of the scanDirExports is sorting the list of files after normalizing them. This is a major drawback as it does not allow you to set an explicit order of directories to scan and therefore of exports to override in case there's another one.

    Example

    When using Nuxt 3 auto-imports, I would expect this option:

    imports: {
       dirs: ['foo', 'bar']
    }
    

    to let exports from bar override exports from foo, but since the filenames are sorted, exports from foo will always override exports from bar.

    I can make a simple PR to prevent that sorting but I'm not exactly sure why it was there in the first place?

    Thanks for your amazing work 🙏

    opened by yassilah 2
  • fix: cannot remove defined values

    fix: cannot remove defined values

    Using export before import default cannot remove defined values

    origin code

         // file specifier
         import { bar } from 'specifier2'
         export { bar }
         import foo from 'specifier1'
         export { foo }
    

    No need for auto import at this point, but output:

         // file specifier
         import { foo } from 'specifier'   // auto import 
    
         import { bar } from 'specifier2'
         export { bar }
         import foo from 'specifier1' // error
         export { foo }
    
    opened by a145789 2
  • Playground does not work

    Playground does not work

    Disclaimer: this is using npm.

    When trying to run the playground (after an npm i), the server throws the following error:

    [plugin:unimport] s.hasChanged is not a function
    /Users/reinierkaper/personal/unimport/playground/src/main.ts
        at TransformContext.transform (file:///Users/reinierkaper/personal/unimport/playground/vite.config.ts.timestamp-1663630386798.mjs:1067:14)
        at processTicksAndRejections (node:internal/process/task_queues:96:5)
        at async file:///Users/reinierkaper/personal/unimport/playground/node_modules/vite-plugin-inspect/dist/index.mjs:676:23
        at async Object.transform (file:///Users/reinierkaper/personal/unimport/playground/node_modules/vite/dist/node/chunks/dep-557f29e6.js:41102:30)
        at async loadAndTransform (file:///Users/reinierkaper/personal/unimport/playground/node_modules/vite/dist/node/chunks/dep-557f29e6.js:37364:29
    

    System: MacOS 12.5.1 Browser: Chrome 105.0.5195.125 Node: 16.15.1 npm: 8.12.1

    opened by TheDutchCoder 2
  • Missing dependency `vue/compiler-sfc`?

    Missing dependency `vue/compiler-sfc`?

    I forked this repo in order to hunt down a bug with commented out exports (cc: https://github.com/nuxt/framework/issues/7658) and I noticed after npm installing that there's a dependency on vue/compiler-sfc, failing a test. I think it just needs to be @vue/compiler-sfc.

    Side note (and I can open another issue for this if required), when running npm run dev the absolute import test fails as it tries to find a.vue which doesn't exist in the project.

    opened by TheDutchCoder 2
  • error with @vueuse/core preset

    error with @vueuse/core preset

    I using this lib with Vite as

      const ctx = createUnimport({
        presets: ['vue', '@vueuse/core'],
        addons: { vueTemplate: true },
      })
    

    and this configuration gives me

    Error
    TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string or an instance of Buffer or URL. Received undefined
      at __node_internal_captureLargerStackTrace (node:internal/errors:477:5)
      at new NodeError (node:internal/errors:388:5)
      at __node_internal_ (node:internal/fs/utils:673:11)
      at __node_internal_ (node:internal/fs/utils:685:3)
      at Object.openSync (node:fs:591:10)
      at Object.readFileSync (node:fs:467:35)
      at vueuseCore (/Users/amaurytobias/garsa/garsa-pdf/node_modules/.pnpm/[email protected][email protected]/node_modules/unimport/dist/chunks/context.cjs:311:41)
      at /Users/amaurytobias/garsa/garsa-pdf/node_modules/.pnpm/[email protected][email protected]/node_modules/unimport/dist/chunks/context.cjs:547:16
      at Array.flatMap (<anonymous>)
      at resolveBuiltinPresets (/Users/amaurytobias/garsa/garsa-pdf/node_modules/.pnpm/[email protected][email protected]/node_modules/unimport/dist/chunks/context.cjs:544:18)
      at createUnimport (/Users/amaurytobias/garsa/garsa-pdf/node_modules/.pnpm/[email protected][email protected]/node_modules/unimport/dist/chunks/context.cjs:629:29)
      at <anonymous> (/Users/amaurytobias/garsa/garsa-pdf/packages/builder/utils/kit.ts:324:15)
      at Object.<anonymous> (/Users/amaurytobias/garsa/garsa-pdf/node_modules/.pnpm/[email protected][email protected]/node_modules/unplugin/dist/index.js:4:688)
      at writeTypes (/Users/amaurytobias/garsa/garsa-pdf/packages/builder/utils/prepare.ts:130:32)
      at Object.invoke (/Users/amaurytobias/garsa/garsa-pdf/packages/builder/commands/prepare.ts:18:5)
      at _main (/Users/amaurytobias/garsa/garsa-pdf/packages/builder/cli.ts:18:18) {
    code: 'ERR_INVALID_ARG_TYPE'
    }
    

    On unplugin-auto-import the @vueuse/core preset is different on the lines: 14:24

    (unimport)[https://github.com/unjs/unimport/blob/main/src/presets/vueuse-core.ts]

     const path = resolveModule('@vueuse/core/indexes.json')
    const indexesJson = JSON.parse(readFileSync(path!, 'utf-8'))
    _cache = defineUnimportPreset({
        from: '@vueuse/core',
        imports: indexesJson
          .functions
          .filter((i: any) => ['core', 'shared'].includes(i.package))
          .map((i: any) => i.name as string)
          // only include functions with 4 characters or more
          .filter((i: string) => i && i.length >= 4 && !excluded.includes(i))
    })
    

    unplugin-auto-import

    const corePath = resolveModule('@vueuse/core') || process.cwd()
    const path = resolveModule('@vueuse/core/indexes.json')
        || resolveModule('@vueuse/metadata/index.json')
        || resolveModule('@vueuse/metadata/index.json', { paths: [corePath] })
     indexesJson = JSON.parse(readFileSync(path!, 'utf-8'))
    

    idk if this can resolve the issue.

    opened by amaury-tobias 2
  • perf: decrease processing time for exclude regexp

    perf: decrease processing time for exclude regexp

    RegExp performance issue found by @pi0 in some nice debugging. (We are trimming whitespace anyway so doesn't make any difference to our usage.)

    Also refactored Array.from -> for/of which might also slightly improve performance with very large strings by using an iterator.

    bug 
    opened by danielroe 2
  • feat!: auto extract exports

    feat!: auto extract exports

    resolve #103

    Todo:

    • [x] Support PackagePreset
    • [x] Global Cache
    • [ ] Package.json's meta.unimport field support

    Breaking changes:

    • Internal context type change
    • generateTypeDeclarations, getExports become async
    opened by antfu 2
  • chore(deps): update all non-major dependencies

    chore(deps): update all non-major dependencies

    Mend Renovate

    This PR contains the following updates:

    | Package | Change | Age | Adoption | Passing | Confidence | |---|---|---|---|---|---| | @vitest/coverage-c8 | ^0.26.3 -> ^0.27.0 | age | adoption | passing | confidence | | mlly | ^1.0.0 -> ^1.1.0 | age | adoption | passing | confidence | | vite-plugin-inspect | ^0.7.12 -> ^0.7.14 | age | adoption | passing | confidence | | vitest | ^0.26.3 -> ^0.27.0 | age | adoption | passing | confidence |


    Release Notes

    vitest-dev/vitest

    v0.27.0

    Compare Source

       🚨 Breaking Changes
       🚀 Features
       🐞 Bug Fixes
       🏎 Performance
        View changes on GitHub
    unjs/mlly

    v1.1.0

    Compare Source

    Features
    Bug Fixes
    antfu/vite-plugin-inspect

    v0.7.14

    Compare Source

    No significant changes

        View changes on GitHub

    Configuration

    📅 Schedule: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

    🚦 Automerge: Enabled.

    Rebasing: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

    👻 Immortal: This PR will be recreated if closed unmerged. Get config help if that's undesired.


    • [ ] If you want to rebase/retry this PR, check this box

    This PR has been generated by Mend Renovate. View repository job log here.

    opened by renovate[bot] 1
  • vueTemplateAddon replace variables in non setup script component

    vueTemplateAddon replace variables in non setup script component

    Environment

    node 16 Nuxt 3

    Reproduction

    stackblitz sfc playground Nuxt 3 original issue by @FRSgit

    Describe the bug

    As you can see in the SFC Playground, vue prepend _ctx to every variables from the setup. This cause the unimport plugin to replace a variable even if it has been declared it the setup of the component

    Additional context

    No response

    Logs

    No response

    opened by huang-julien 0
  • Opt-out for auto-import

    Opt-out for auto-import

    Describe the feature

    The auto-import feature is convenient to use but sometimes could be confusing when users accidentally introduce circular auto-import references for accidentally introducing unnecessary references to some modules. Being about to opt-out auto-import for some modules could help to make some parts better organized.

    Here are a few raw ideas:

    1. Magic comments

    We could do a quick RegExp check in the transforming phase to have fine-grained opt-out of some modules:

    // @imports-disable
    // @unimport-disable
    

    2. Configuration

    I guess it's already possible by setting the exclude options to exclude by globs.

    Unimport({
      exclude: [
        'composables/**'
      ]
    }
    

    The issue we could need to solve might be to opt-out of the global TypeScript declarations for those modules.

    3. Auto-injected magic comments

    Taking it a bit further, we might do automatic import injection. We could have a comment marking the module as:

    // @unimport-auto-inject
    import { foo } from './foo'
    

    And once you used a new import from the auto-import registry, let say bar:

    // @unimport-auto-inject
    import { foo } from './foo'
    
    console.log(bar)
    

    In development mode, we could inject the bar import automatically. Once we save the file, unimport will see the new usage communing and inject it like this:

    // @unimport-auto-inject
    + import { bar } from './bar' // auto injected on save
    import { foo } from './foo'
    
    console.log(bar)
    

    This way, it can help users make clear what and where the imports are auto-imported without worrying them too much.

    Additional information

    • [X] Would you be willing to help implement this feature?
    opened by antfu 0
  • Dependency Dashboard

    Dependency Dashboard

    This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

    Open

    These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

    Detected dependencies

    github-actions
    .github/workflows/ci.yml
    • actions/checkout v3
    • pnpm/action-setup v2
    • actions/setup-node v3
    • codecov/codecov-action v3
    npm
    package.json
    • @rollup/pluginutils ^5.0.2
    • escape-string-regexp ^5.0.0
    • fast-glob ^3.2.12
    • local-pkg ^0.4.2
    • magic-string ^0.27.0
    • mlly ^1.0.0
    • pathe ^1.0.0
    • pkg-types ^1.0.1
    • scule ^1.0.0
    • strip-literal ^1.0.0
    • unplugin ^1.0.1
    • @nuxtjs/eslint-config-typescript ^12.0.0
    • @vitest/coverage-c8 ^0.26.3
    • eslint ^8.31.0
    • h3 ^1.0.2
    • jquery ^3.6.3
    • standard-version ^9.5.0
    • typescript ^4.9.4
    • unbuild ^1.0.2
    • vitest ^0.26.3
    • vue-tsc ^1.0.24
    • pnpm 7.23.0
    playground/package.json
    • vue ^3.2.45
    • @vitejs/plugin-vue ^4.0.0
    • typescript ^4.9.4
    • vite ^4.0.4
    • vite-plugin-inspect ^0.7.12

    • [ ] Check this box to trigger a request for Renovate to run again on this repository
    opened by renovate[bot] 0
Owner
unjs
Unified JavaScript Tools
unjs
⭐️ Auto create alias map for vite config

vite-plugin-tspaths2alias This plugin is create alias map for vite config, default use project root tsconfig.json file compilerOptions.paths value Ins

yankit 2 Mar 26, 2022
Auto generate the corresponding `.env` file.

unplugin-vue-dotenv Auto generate the corresponding .env file. Install npm i unplugin-vue-dotenv Vite // vite.config.ts import Dotenv from 'unplugin-v

Chris 6 Dec 24, 2022
End-to-end typesafe APIs with tRPC.io in Nuxt applications.

tRPC-Nuxt End-to-end typesafe APIs with tRPC.io in Nuxt applications. The client above is not importing any code from the server, only its type declar

Robert Soriano 231 Dec 30, 2022
Automatically detect and import components or modules

vite-plugin-autoimport Automatically detect and import components or modules. Motivation It's very common to have many components in one file as the p

Yuan Chuan 146 Dec 23, 2022
Write CSS modules without leaving your javascript!

vite-plugin-inline-css-modules Write CSS modules without leaving your javascript! Zero Runtime Contains full feature set of CSS modules (Includes Post

Blusk 39 Jan 2, 2023
Adds links to Discogs pages from various sites. Auto search for music on torrent and other sites. Does multi auto-search on Artist/Discography pages. Auto search local HDDs/filelists using Voidtools Everything search engine.

Discogs Scout: Adds links to Discogs pages from various sites. Auto search for music on torrent and other sites. Does multi auto-search on Artist/Disc

null 27 Dec 27, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
A tool to simplify importing custom assets in Minecraft

BAMO - Block And Move On A tool to simplify importing custom assets in Minecraft Currently only allows you to quickly prototype models in-game, but fu

Tom Mudway 3 Jul 15, 2022
Webpack plugin that helps importing .cdc files

cadence-webpack-plugin Webpack plugin that helps importing .cdc files and polyfills fcl dependencies This fixes the Buffer is not defined and Module n

AE Studio 8 Dec 8, 2022
This simple library allows you to create awesome responsive and highly customizable popups importing just one JavaScript file.

Creativa - Popup This is a simple library that allows you to create awesome popups importing just one JavaScript file. Getting started You can import

Eduardo Mollo 5 Mar 29, 2022
three.js loader for importing M2 assets from World of Warcraft.

three-m2loader · M2 Loader for three.js three-m2loader allows you to import M2 assets from World of Warcraft into your three.js app. druidcat2.m2 7ne_

Michael Herzog 14 Dec 30, 2022
Mimic tree-shaking behaviour when importing code from an entry file in development mode.

vite-plugin-entry-shaking Mimic tree-shaking behaviour when importing code from an entry file in development mode. Warning This plugin is experimental

n028 11 Dec 19, 2022
local storage wrapper for both react-native and browser. Support size controlling, auto expiring, remote data auto syncing and getting batch data in one query.

react-native-storage This is a local storage wrapper for both react native apps (using AsyncStorage) and web apps (using localStorage). ES6 syntax, pr

Sunny Luo 2.9k Dec 16, 2022
auto create and auto verif otp vconomics ! udah coid awkaowkaw

Vconomics Refferal Bot How to use : git clone https://github.com/dkmpostor/vconomics/ cd vconomics npm install node index.js Input refferal code Done

DK 2 Jan 10, 2022
ppo is a super small and useful utils library for JavaScript 🐝🐜

Overview Every frontend developer has written his own utils library, and we often write methods that are easily forgotten and highly used. ppo is a su

anonymous namespace 105 Jul 21, 2022