Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for self-referencing the current package in tests #1394

Closed
4 tasks done
ifiokjr opened this issue May 29, 2022 · 2 comments
Closed
4 tasks done

Add support for self-referencing the current package in tests #1394

ifiokjr opened this issue May 29, 2022 · 2 comments

Comments

@ifiokjr
Copy link

ifiokjr commented May 29, 2022

Clear and concise description of the problem

As a user of vitest I would like to self reference the current package by name when importing in a test. This is a builtin node feature for projects which specify "type": "module".

Given a folder structure of:

my-package/
├─ package.json
├─ index.js
├─ tests/
│  ├─ my-package.spec.js

And files with this content:

// my-package/package.json

{
  "name": "my-package",
  "type": "module",
  "exports": "./index.js"
}
// my-package/tests/my-package.spec.js

import myPackage from 'my-package';
import { test, expect } from 'vitest';

test('myPackage', () => {
  expect(myPackage).toBeTruthy();
})

I would like to be able to write the following in the test folder. Currently, when I do this I get the following error:

- Error: [vite-node] Failed to load my-package

Suggested solution

I'm not sure whether this is a request that should be raised in vite, or should be added as a vite-plugin.

Example

Here is a reproduction of the current issue faced: https://stackblitz.com/edit/github-w9fjy7-bba6ny?file=my-package.spec.js

@antfu
Copy link
Member

antfu commented May 29, 2022

You can set alias in your vite.config.ts

export default defineConfig({
  resolve: {
    alias: {
      'my-package': resolve('./src/index.ts')
    }
  }
})

@antfu antfu closed this as completed May 29, 2022
@ifiokjr
Copy link
Author

ifiokjr commented May 29, 2022

Thanks @antfu this works.

In a monorepo environment with multiple packages, each package will have to be added as an alias, which means all packages will be available from all test code regardless of location.

Ideally, the location of the test should determine how self-reference package names are resolved.

I'll see if I can create a general purpose vite plugin to handle this.

@github-actions github-actions bot locked and limited conversation to collaborators Jun 18, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants