aleclarson / vite-tsconfig-paths

Support for TypeScript's path mapping in Vite
MIT License
1.28k stars 45 forks source link

Support Vite resource import #35

Closed liuzw2579 closed 2 years ago

liuzw2579 commented 3 years ago

vite can import file use ?raw or ?url and so on, when use it, plugin can't resolveId should substring it:

 if (/.+\?.*$/.test(id)) {
     id = id.split('?')[0]
 }
aleclarson commented 3 years ago

There's a PR for this #29

I just haven't had time to review it

nightah commented 2 years ago

TLDR: Read the edit at the bottom.

Seems that including the patch in #29 did not resolve the issue for me.

With the following configuration: vite.ts.config:

import path from "path";

import reactRefresh from "@vitejs/plugin-react-refresh";
import { defineConfig, loadEnv } from "vite";
import eslintPlugin from "vite-plugin-eslint";
import istanbul from "vite-plugin-istanbul";
import svgr from "vite-plugin-svgr";
import tsconfigPaths from "vite-tsconfig-paths";

// @ts-ignore
export default defineConfig(({ mode }) => {
    const env = loadEnv(mode, "env");
    const isCoverage = process.env.VITE_COVERAGE === "true";
    const sourcemap = isCoverage ? "inline" : undefined;

    const htmlPlugin = () => {
        return {
            name: "html-transform",
            transformIndexHtml(html: string) {
                return html.replace(/%(.*?)%/g, function (match, p1) {
                    return env[p1];
                });
            },
        };
    };

    const istanbulPlugin = isCoverage
        ? istanbul({
              include: "src/*",
              exclude: ["node_modules"],
              extension: [".js", ".jsx", ".ts", ".tsx"],
              requireEnv: true,
          })
        : undefined;

    return {
        base: "./",
        build: {
            sourcemap,
            outDir: "../internal/server/public_html",
            assetsDir: "static",
            rollupOptions: {
                output: {
                    entryFileNames: `static/js/[name].[hash].js`,
                    chunkFileNames: `static/js/[name].[hash].js`,
                    assetFileNames: ({ name }) => {
                        if (name && name.endsWith(".css")) {
                            return "static/css/[name].[hash].[ext]";
                        }

                        return "static/media/[name].[hash].[ext]";
                    },
                },
            },
        },
        server: {
            open: false,
            hmr: {
                clientPort: env.VITE_HMR_PORT || 3000,
            },
        },
        plugins: [eslintPlugin(), htmlPlugin(), istanbulPlugin, reactRefresh(), svgr(), tsconfigPaths({ loose: true })],
    };
});

tsconfig.json:

{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@root/*": ["./*"],
      "@assets/*": ["assets/*"],
      "@components/*": ["components/*"],
      "@constants/*": ["constants/*"],
      "@hooks/*": ["hooks/*"],
      "@layouts/*": ["layouts/*"],
      "@models/*": ["models/*"],
      "@services/*": ["services/*"],
      "@themes/*": ["themes/*"],
      "@utils/*": ["utils/*"],
      "@views/*": ["views/*"]
    },
    "target": "es6",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "types": ["@types/node", "vite/client", "vite-plugin-svgr/client"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  }
}

~~You can reproduce the issue by cloning the the following repo with the included patch which removes the in place workaround: https://github.com/authelia/authelia~~

Index: web/vite.config.ts
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
diff --git a/web/vite.config.ts b/web/vite.config.ts
--- a/web/vite.config.ts    (revision 2853a8e56a86fa2590aca2abbb8f8cd9df8a56e4)
+++ b/web/vite.config.ts    (date 1633997017579)
@@ -1,5 +1,3 @@
-import path from "path";
-
 import reactRefresh from "@vitejs/plugin-react-refresh";
 import { defineConfig, loadEnv } from "vite";
 import eslintPlugin from "vite-plugin-eslint";
@@ -59,14 +57,6 @@
                 clientPort: env.VITE_HMR_PORT || 3000,
             },
         },
-        resolve: {
-            alias: [
-                {
-                    find: "@components",
-                    replacement: path.resolve(__dirname, "src/components"),
-                },
-            ],
-        },
-        plugins: [eslintPlugin(), htmlPlugin(), istanbulPlugin, reactRefresh(), svgr(), tsconfigPaths()],
+        plugins: [eslintPlugin(), htmlPlugin(), istanbulPlugin, reactRefresh(), svgr(), tsconfigPaths({ loose: true })],
     };
 });
Index: web/tsconfig.json
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
diff --git a/web/tsconfig.json b/web/tsconfig.json
--- a/web/tsconfig.json (revision 2853a8e56a86fa2590aca2abbb8f8cd9df8a56e4)
+++ b/web/tsconfig.json (date 1633996862882)
@@ -34,16 +34,5 @@
     "isolatedModules": true,
     "noEmit": true,
     "jsx": "react-jsx"
-  },
-  "include": [
-    ".*.js",
-    "vite.config.ts",
-    "src",
-    "types"
-  ],
-  "exclude": [
-    "node_modules",
-    "build",
-    "coverage"
-  ]
+  }
 }

Also for clarity it fails with the following error:

[vite]: Rollup failed to resolve import "@components/FingerTouchIcon.module.css?used" from "src/components/FingerTouchIcon.tsx".
This is most likely unintended because it can break your application at runtime.
If you do want to externalize this module explicitly add it to
`build.rollupOptions.external`
error during build:
Error: [vite]: Rollup failed to resolve import "@components/FingerTouchIcon.module.css?used" from "src/components/FingerTouchIcon.tsx".
This is most likely unintended because it can break your application at runtime.
If you do want to externalize this module explicitly add it to
`build.rollupOptions.external`
    at onRollupWarning (/srv/repos/authelia/web/node_modules/vite/dist/node/chunks/dep-713b45e1.js:43249:19)
    at onwarn (/srv/repos/authelia/web/node_modules/vite/dist/node/chunks/dep-713b45e1.js:43033:13)
    at Object.onwarn (/srv/repos/authelia/web/node_modules/rollup/dist/shared/rollup.js:22917:13)
    at ModuleLoader.handleResolveId (/srv/repos/authelia/web/node_modules/rollup/dist/shared/rollup.js:22265:26)
    at /srv/repos/authelia/web/node_modules/rollup/dist/shared/rollup.js:22257:26
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Process finished with exit code 1

EDIT:

It looks like the changes actually do work however, if there are no includes excludes in my tsconfig.json the following error occurs:

[vite:tsconfig-paths] The argument 'path' must be a string or Uint8Array without null bytes. Received '/srv/repos/authelia/web/src/\x00commonjsHelpers.js'
error during build:
TypeError [PLUGIN_ERROR]: The argument 'path' must be a string or Uint8Array without null bytes. Received '/srv/repos/authelia/web/src/\x00commonjsHelpers.js'
    at Object.stat (node:fs:1458:10)
    at fileExistsAsync (/srv/repos/authelia/web/node_modules/.pnpm/vite-tsconfig-paths@3.3.15_vite@2.6.7/node_modules/vite-tsconfig-paths/node_modules/.pnpm/tsconfig-paths@3.11.0/node_modules/tsconfig-paths/lib/filesystem.js:41:8)
    at findFirstExistingPath (/srv/repos/authelia/web/node_modules/.pnpm/vite-tsconfig-paths@3.3.15_vite@2.6.7/node_modules/vite-tsconfig-paths/node_modules/.pnpm/tsconfig-paths@3.11.0/node_modules/tsconfig-paths/lib/match-path-async.js:66:9)
    at matchFromAbsolutePathsAsync (/srv/repos/authelia/web/node_modules/.pnpm/vite-tsconfig-paths@3.3.15_vite@2.6.7/node_modules/vite-tsconfig-paths/node_modules/.pnpm/tsconfig-paths@3.11.0/node_modules/tsconfig-paths/lib/match-path-async.js:31:5)
    at /srv/repos/authelia/web/node_modules/.pnpm/vite-tsconfig-paths@3.3.15_vite@2.6.7/node_modules/vite-tsconfig-paths/node_modules/.pnpm/tsconfig-paths@3.11.0/node_modules/tsconfig-paths/lib/match-path-async.js:15:16
    at /srv/repos/authelia/web/node_modules/.pnpm/vite-tsconfig-paths@3.3.15_vite@2.6.7/node_modules/vite-tsconfig-paths/dist/index.js:109:9
    at new Promise (<anonymous>)
    at resolveWithPaths (/srv/repos/authelia/web/node_modules/.pnpm/vite-tsconfig-paths@3.3.15_vite@2.6.7/node_modules/vite-tsconfig-paths/dist/index.js:108:63)
    at resolveId (/srv/repos/authelia/web/node_modules/.pnpm/vite-tsconfig-paths@3.3.15_vite@2.6.7/node_modules/vite-tsconfig-paths/dist/index.js:119:50)
    at /srv/repos/authelia/web/node_modules/.pnpm/vite-tsconfig-paths@3.3.15_vite@2.6.7/node_modules/vite-tsconfig-paths/dist/index.js:139:23
 ELIFECYCLE  Command failed with exit code 1.
aleclarson commented 2 years ago

Fixed in v3.3.16