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

Vite can't import from index.tsx after moving to nxViteTsPaths #19349

Closed
4 tasks
galarbel opened this issue Sep 27, 2023 · 10 comments
Closed
4 tasks

Vite can't import from index.tsx after moving to nxViteTsPaths #19349

galarbel opened this issue Sep 27, 2023 · 10 comments
Assignees
Labels
outdated scope: bundlers Issues related to webpack, rollup type: bug

Comments

@galarbel
Copy link

galarbel commented Sep 27, 2023

Current Behavior

after upgrading to nx 16 vite fails to resolve imports from other libs when using exports from index.tsx files.

image

this was fine prior to the nxViteTsPaths change.

this works:

// vite.config.ts
...
import viteTsConfigPaths from "vite-tsconfig-paths";

...

plugins: [
  ...
  viteTsConfigPaths({
      root: "../../",
    }),
  ...
]

while the new format - doesn't work


// vite.config.ts
...
import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin';

...

plugins: [
  ...
  nxViteTsPaths()
  ...
]
...

Expected Behavior

the new nxViteTsPaths() will work similar to viteTsConfigPaths and resolve imports correctly.

GitHub Repo

No response

Steps to Reproduce

prerequisites:

  1. react app
  2. react components lib

steps:

  1. setup tsconfig.base.json with the paths:
...
"compilerOptions": {
  ...
  "paths": { "@my-lib/*" : ["libs/my-lib/src/*"],
  ...
}
  1. create a component in libs/my-lib/src/components/Test.tsx
  2. create an index.tsx file in your lib - libs/my-lib/src/components/index.tsx
  3. add to index.tsx export { default as TestComponent } from "./Test"
  4. in the react app the import of the component
import { TestComponent  } from "@my-lib/components"

with old viteconfig this works, with new one it doesn't

Nx Report

>  NX   Report complete - copy this into the issue template

   Node   : 18.16.0
   OS     : win32-x64
   pnpm   : 8.3.0
   
   nx                 : 16.9.1
   @nx/js             : 16.9.1
   @nx/jest           : 16.9.1
   @nx/linter         : 16.9.1
   @nx/workspace      : 16.9.1
   @nx/cypress        : 16.9.1
   @nx/devkit         : 16.9.1
   @nx/eslint-plugin  : 16.9.1
   @nx/react          : 16.9.1
   @nx/storybook      : 16.9.1
   @nrwl/tao          : 16.9.1
   @nx/vite           : 16.9.1
   @nx/web            : 16.9.1
   @nx/webpack        : 16.9.1
   nx-cloud           : 16.4.0
   typescript         : 5.1.6

Failure Logs

No response

Package Manager Version

No response

Operating System

  • macOS
  • Linux
  • Windows
  • Other (Please specify)

Additional Information

this seems somewhat related to #18492, but not quite

@galarbel
Copy link
Author

if it helps others -
our current workaround is to revert the vite.config.ts change.

our current vite.config.ts file is this:

/* eslint-disable import/no-extraneous-dependencies */
/// <reference types="vitest" />
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import viteTsConfigPaths from "vite-tsconfig-paths";
// import { nxViteTsPaths } from '@nx/vite/plugins/nx-tsconfig-paths.plugin'; // removed since does not support index.tsx files
import basicSsl from "@vitejs/plugin-basic-ssl";
import eslint from "vite-plugin-eslint";
import svgr from "vite-plugin-svgr";

export default defineConfig({
  cacheDir: "../../node_modules/.vite/backoffice",

  server: {
    port: 3001,
    host: "localhost",
    https: true,
  },

  preview: {
    port: 4301,
    host: "localhost",
  },

  plugins: [
    svgr(),
    react(),
    viteTsConfigPaths({
      root: "../../",
    }),
    // nxViteTsPaths(), // see comment on import
    basicSsl(),
    eslint(),
  ],

  // Uncomment this if you are using workers.
  // worker: {
  //  plugins: [
  //    viteTsConfigPaths({
  //      root: '../../',
  //    }),
  //  ],
  // },

  test: {
    globals: true,
    cache: {
      dir: "../../node_modules/.vitest",
    },
    environment: "jsdom",
    include: ["src/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}"],
  },
});

@iceStorm
Copy link

iceStorm commented Sep 27, 2023

One more issue. I'm getting extra-redundant fields inside my vite.config.ts files.

image

Just scaffolded a new project and when start bundling, i'm stressed out with these changes...

Scenario:

  • When generating a react library, with bundler = vite.
  • Nx version: 16.9.1
  • Package manager: pnpm
  • Node: 18.17.0
  • OS: MacOS Ventura 13.5.2 - M1 chip.

P/S: This issue also happens in Nx 16.8.7.

@AgentEnder AgentEnder added the scope: bundlers Issues related to webpack, rollup label Sep 27, 2023
@KonstantinKai
Copy link

I'm experiencing the same issue for module subfolders with index files.

@KonstantinKai
Copy link

KonstantinKai commented Sep 28, 2023

After some research, I've found some causes with the @nx/vite/plugin/nx-tsconfig-paths.plugin and tsconfig-paths library

  • about the plugin. I think we should pass options.extensions to matchTsPathEsm and matchTsPathFallback because, by default, they use Object.keys(require.extensions), which misses tsx? extensions. That causes redundant cycles for file searching.
  • about the tsconfig-paths library. I think it doesn't fit 100% for the plugin because the library is adapted to use with node runtime. They have getStrippedPath function that trims the found path, which doesn't fit in our case. It will be great to customize this behavior through createMatchPath.

I did do the following things, and my project was built OK.

// package: @nx/vite
// file: nx-tsconfig-paths.plugin.ts
resolveId(importPath: string) {
  let resolvedFile: string;
  try {
    resolvedFile = matchTsPathEsm(
      importPath,
      undefined,
      undefined,
      options.extensions
    );
  } catch (e) {
    logIt('Using fallback path matching.');
    resolvedFile = matchTsPathFallback?.(
      importPath,
      undefined,
      undefined,
      options.extensions
    );
  }

  if (!resolvedFile) {
    if (tsConfigPathsEsm || tsConfigPathsFallback) {
      logIt(
        `Unable to resolve ${importPath} with tsconfig paths. Using fallback file matching.`
      );
      resolvedFile =
        loadFileFromPaths(tsConfigPathsEsm, importPath) ||
        loadFileFromPaths(tsConfigPathsFallback, importPath);
    } else {
      logIt(`Unable to resolve ${importPath} with tsconfig paths`);
    }
  }

  logIt(`Resolved ${importPath} to ${resolvedFile}`);
  // Returning null defers to other resolveId functions and eventually the default resolution behavior
  // https://rollupjs.org/plugin-development/#resolveid
  return resolvedFile || null;
},

// package: tsconfig-paths
// file: try-path.ts
export function getStrippedPath(tryPath: TryPath): string {
  return ["extension", "file", "index", "package"].indexOf(
    tryPath.type
  ) !== -1
    ? tryPath.path
    : exhaustiveTypeException(tryPath.type as never);
}

STR file tree:

- libs
  - lib1
    - src
      - lib
        - folder1
          - index.ts
      - index.ts

STR tsconfig paths:

"paths": {
  "@/lib1": ["./libs/lib1/src/index.ts"],
  "@/lib1/*": ["./libs/lib1/src/lib/*"]
}

STR import string:

import a from '@/lib1/folder1';

My Nx report:

Node   : 18.18.0                                                                                                                                               │Untracked files:
OS     : darwin-x64                                                                                                                                            │  (use "git add <file>..." to include in what will be committed)
npm    : 8.19.1                                                                                                                                                │        apps/studio/src/misc/isManager.ts
                                                                                                                                                               │
nx                 : 16.9.1                                                                                                                                    │no changes added to commit (use "git add" and/or "git commit -a")
@nx/js             : 16.9.1                                                                                                                                    │➜  cnt-admin git:(develop) ✗ g add .
@nx/jest           : 16.9.1                                                                                                                                    │➜  cnt-admin git:(develop) ✗ g status
@nx/linter         : 16.9.1                                                                                                                                    │On branch develop
@nx/workspace      : 16.9.1                                                                                                                                    │Changes to be committed:
@nx/cypress        : 16.9.1                                                                                                                                    │  (use "git restore --staged <file>..." to unstage)
@nx/devkit         : 16.9.1                                                                                                                                    │        new file:   apps/studio/src/misc/isManager.ts
@nx/eslint-plugin  : 16.9.1                                                                                                                                    │        modified:   apps/studio/src/router.tsx
@nx/react          : 16.9.1                                                                                                                                    │        modified:   apps/studio/src/ui/App.tsx
@nrwl/tao          : 16.9.1                                                                                                                                    │
@nx/vite           : 0.0.1                                                                                                                                     │➜  cnt-admin git:(develop) ✗ g commit -am 'fix: disable intercom for
@nx/web            : 16.9.1                                                                                                                                    │manage
typescript         : 5.2.2         

PS: @nx/vite@0.0.1 my local copy with suggested changes of @nx/vite@16.9.1

@KonstantinKai
Copy link

There exists the PR for this #19030

But, it solves the problem in a fallback section

@Cukac
Copy link

Cukac commented Dec 21, 2023

I have the same problem but without vite and nxViteTsPaths.
The problem arises in react-native app:

success Successfully launched the app on the simulator
[Nx] Resolving: ./index
[Nx] Unable to resolve with default resolveRequest: ./index
[Nx] Unable to resolve with default Metro resolver: ./index
[Nx] Located tsconfig at /Users/cuky/code/vbt/fresh-artmate
[Nx] Found the following paths:
:{
  "@my-app/domain": [
    "libs/domain/src/index"
  ],
  "@my-app/migrations": [
    "libs/migrations/src/index"
  ],
  "@my-app/schemas": [
    "libs/schemas/src/index"
  ],
  "@my-app/utils": [
    "libs/domain/src/utils/index"
  ]
}
[Nx] Failed to resolve ./index
[Nx] The following tsconfig paths was used:
:{
  "@my-app/domain": [
    "libs/domain/src/index"
  ],
  "@my-app/migrations": [
    "libs/migrations/src/index"
  ],
  "@my-app/schemas": [
    "libs/schemas/src/index"
  ],
  "@my-app/utils": [
    "libs/domain/src/utils/index"
  ]
}
[Nx] Unable to resolve with default PNPM resolver: ./index
Error: Cannot resolve ./index

After full day of debugging (this is just my last try of removing extensions from index files, original is with index.ts paths),
I found that my solution should be adding nxViteTsPaths.
But I wanted to investigate it a bit further and stumbled on this...
So... it seems this is not going to fix my problem also...

@fsgreco
Copy link

fsgreco commented Jan 7, 2024

Hi eveybody, I've just found a new solution for this, explained everything in detail here: #21030

TL;DR: you can change the paths alias inside the tsconfig.base.json, as long as it does not match the name of the custom package/library it will work fine (I talk about the name property inside its package.json). I still think that it's a bug but at least this seems an easy and not invasive solution.

@Demianeen
Copy link

Demianeen commented Feb 29, 2024

For everybody here, I think the new version fixed that already.

I added the same lines to findFile function and that did the trick for me.

In my case I needed to add:

const resolvedIndexPath = (0, _nodepath.resolve)(path, `index${ext}`)
if ((0, _nodefs.existsSync)(resolvedIndexPath)) {
	return resolvedIndexPath
}

@Coly010
Copy link
Contributor

Coly010 commented May 16, 2024

Closed as fixed: #21513

@Coly010 Coly010 closed this as completed May 16, 2024
Copy link

This issue has been closed for more than 30 days. If this issue is still occuring, please open a new issue with more recent context.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Jun 17, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
outdated scope: bundlers Issues related to webpack, rollup type: bug
Projects
None yet
Development

No branches or pull requests

8 participants