Erros no npm run build no projeto vue - resolvido

Alguns erros

src/stores/apps/tema.ts:5:25 - error TS2339: Property 'env' does not exist on type 'ImportMeta'.
5 const url = import.meta.env.VITE_APP_BACKEND_URL;
                          ~~~
src/stores/auth.ts:5:32 - error TS2339: Property 'env' does not exist on type 'ImportMeta'.
5 const baseUrl = `${import.meta.env.VITE_API_URL}/users`;
                                 ~~~
src/stores/authUser.ts:5:32 - error TS2339: Property 'env' does not exist on type 'ImportMeta'.
5 const baseUrl = `${import.meta.env.VITE_API_URL}/users`;
                                ~~~
src/utils/helpers/fetch-wrapper.ts:30:47 - error TS2339: Property 'env' does not exist on type 'ImportMeta'.
30   const isApiUrl = url.startsWith(import.meta.env.VITE_API_URL);

outros

src/_mockApis/components/widget/card.ts:36:19 - error TS2307: Cannot find module '@/assets/images/svgs/icon-master-card.svg' or its corresponding type declarations.
36 import icon3 from "@/assets/images/svgs/icon-master-card.svg";
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/_mockApis/components/widget/card.ts:37:19 - error TS2307: Cannot find module '@/assets/images/svgs/icon-pie.svg' or its corresponding type declarations.
37 import icon4 from "@/assets/images/svgs/icon-pie.svg";
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/_mockApis/headerData.ts:8:19 - error TS2307: Cannot find module '@/assets/images/profile/user-1.jpg' or its corresponding type declarations.
8 import user1 from '@/assets/images/profile/user-1.jpg';
                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/_mockApis/headerData.ts:9:19 - error TS2307: Cannot find module '@/assets/images/profile/user-2.jpg' or its corresponding type declarations.
9 import user2 from '@/assets/images/profile/user-2.jpg';

tsconfig.json

{
  "extends": "@vue/tsconfig/tsconfig.web.json",
  "include": ["env.d.ts", "src/**/*", "src/**/*.vue"],
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    },
    "allowJs": true,
    "types": ["node"],
  },
  "references": [
    {
      "path": "./tsconfig.vite-config.json"
    }
  ]
}

tsconfig.vite-config.json

{
  "extends": "@vue/tsconfig/tsconfig.node.json",
  "include": ["vite.config.*"],
  "compilerOptions": {
    "composite": true,
    "allowJs": true,
    "types": ["node"]
  }
}

O que pode ser ?

adiciona isso dentro do seu tsconfig.json

{
  ...
  "compilerOptions": {
    ...
    "target": "ESNext",
    "types": ["vite/client"]
  }
}

  • crie uma pasta chamada @types dentro de src
  • crie um arquivo chamado index.d.ts
  • cola esse trecho abaixo:
declare module '*.jpg';
declare module '*.png';
declare module '*.svg';
1 curtida

Obrigado @rodriguesabner

Deu este erro agora

vite v4.1.1 building for production…
transforming (841) node_modules\vuetify\lib\components\VCounter\index.mjsnode_modules/js-sha256/src/sha256.js (83:17) Use of eval in “node_modules/js-sha256/src/sha256.js” is strongly discouraged as it poses security risks and may cause issues with minification.
node_modules/js-sha256/src/sha256.js (84:17) Use of eval in “node_modules/js-sha256/src/sha256.js” is strongly discouraged as it poses security risks and may cause issues with minification.
✓ 876 modules transformed.
rendering chunks (12)…[vite:esbuild-transpile] Transform failed with 2 errors:
assets/index-!~{001}~.js:167040:24: ERROR: Top-level await is not available in the configured target environment (“chrome87”, “edge88”, “es2020”, “firefox78”, “safari14” + 2 overrides)
assets/index-!~{001}~.js:167046:18: ERROR: Top-level await is not available in the configured target environment (“chrome87”, “edge88”, “es2020”, “firefox78”, “safari14” + 2 overrides)

Top-level await is not available in the configured target environment (“chrome87”, “edge88”, “es2020”, “firefox78”, “safari14” + 2 overrides)
167038| });
167039| try {
167040| const authenticated = await keycloak.init({
| ^
167041| onLoad: “login-required”
167042| });

Top-level await is not available in the configured target environment (“chrome87”, “edge88”, “es2020”, “firefox78”, “safari14” + 2 overrides)
167044| User is ${authenticated ? "authenticated" : "not authenticated"}
167045| );
167046| const profile = await keycloak.loadUserProfile();
| ^
167047| console.log(profile is ${profile});
167048| localStorage.setItem(“token”, keycloak.token);

error during build:
Error: Transform failed with 2 errors:
assets/index-!~{001}~.js:167040:24: ERROR: Top-level await is not available in the configured target environment (“chrome87”, “edge88”, “es2020”, “firefox78”, “safari14” + 2 overrides)
assets/index-!~{001}~.js:167046:18: ERROR: Top-level await is not available in the configured target environment (“chrome87”, “edge88”, “es2020”, “firefox78”, “safari14” + 2 overrides)
at failureErrorWithLog (C:\sistemas\workspace\bedtech-novo\frontend\node_modules\vite\node_modules\esbuild\lib\main.js:1604:15)
at C:\sistemas\workspace\bedtech-novo\frontend\node_modules\vite\node_modules\esbuild\lib\main.js:837:29
at responseCallbacks. (C:\sistemas\workspace\bedtech-novo\frontend\node_modules\vite\node_modules\esbuild\lib\main.js:701:9)
at handleIncomingPacket (C:\sistemas\workspace\bedtech-novo\frontend\node_modules\vite\node_modules\esbuild\lib\main.js:756:9)
at Socket.readFromStdout (C:\sistemas\workspace\bedtech-novo\frontend\node_modules\vite\node_modules\esbuild\lib\main.js:677:7)
at Socket.emit (node:events:513:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)
at Pipe.onStreamRead (node:internal/stream_base_commons:190:23)

Pesquisei achei algumas coisas, mas não entendi.

O que pode ser ?

esses dois aí: await keycloak.... tão sendo chamado fora de um escopo async, parece estar solto no código. Só ajustar eles e GG

1 curtida

Fiz assim e funcionou

async () => {
  try {
    const authenticated = await keycloak.init({
      onLoad: "login-required",
    });
    console.log(
      `User is ${authenticated ? "authenticated" : "not authenticated"}`
    );
    const profile = await keycloak.loadUserProfile();
    console.log(`profile is ${profile}`);
    localStorage.setItem("token", keycloak.token as string);
    localStorage.setItem("refreshToken", keycloak.refreshToken as string);
    localStorage.setItem("user", keycloak.refreshToken as string);
    localStorage.setItem("profile", JSON.stringify(profile));
    //Token Refresh
    setInterval(() => {
      keycloak
        .updateToken(70)
        .then((refreshed) => {
          if (refreshed) {
            console.log("Token refreshed");
          } else {
            console.warn("Token not refreshed");
          }
        })
        .catch(() => {
          console.error("Failed to refresh token");
        });
    }, 6000);
  } catch (error) {
    console.error("Failed to initialize adapter:", error);
  }
};

Local funcionou, mas quando fez o deploy no servidor deu este erro:

150 packages are looking for funding
  run `npm fund` for details
found 35 vulnerabilities (33 moderate, 2 high)
  run `npm audit fix` to fix them, or `npm audit` for details
$ npm run build --mode homologacao
> quizme@0.0.1 build /builds/prefitech/bedtech/frontend
> vue-tsc --noEmit && vite build "homologacao"
file:///builds/prefitech/bedtech/frontend/node_modules/vite/bin/vite.js:7
    await import('source-map-support').then((r) => r.default.install())
    ^^^^^
SyntaxError: Unexpected reserved word
    at Loader.moduleStrategy (internal/modules/esm/translators.js:140:18)
    at async link (internal/modules/esm/module_job.js:42:21)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! quizme@0.0.1 build: `vue-tsc --noEmit && vite build "homologacao"`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the quizme@0.0.1 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2023-10-23T17_51_32_982Z-debug.log

q versão do node vc ta usando? tenta >=16

1 curtida

Com node:16, este erro

Run `npm audit` for details.
$ npm run build --mode homologacao
> quizme@0.0.1 build
> vue-tsc --noEmit && vite build homologacao
vite v4.1.1 building for production...
✓ 0 modules transformed.
Could not resolve entry module "homologacao/index.html".
error during build:
RollupError: Could not resolve entry module "homologacao/index.html".
    at error (file:///builds/prefitech/bedtech/frontend/node_modules/rollup/dist/es/shared/node-entry.js:2287:30)
    at ModuleLoader.loadEntryModule (file:///builds/prefitech/bedtech/frontend/node_modules/rollup/dist/es/shared/node-entry.js:24881:20)
    at async Promise.all (index 0)
Cleaning up project directory and file based variables
00:00
ERROR: Job failed: exit code 1

vc tem um .html nos seus arquivos?

1 curtida

Tem

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link
    rel="stylesheet"
    href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Poppins:wght@400;500;600;700&family=Roboto:wght@400;500;700&display=swap"
    />
    <title>QuizMe</title>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>

mostra a estrutura dos arquivos

1 curtida

mostra o arquivo vite config ou algum lugar q vc botou esse /homologacao aí. Não existe essa pasta…

1 curtida

image

image

tira esse homologacao aí. O correto é vite build. Isso ta no package.json

1 curtida

notei que vc tem um --mode homologacao no action do git. Ao invés de tirar, pode trocar também… Aí ficaria:

"build": "tsc && vite build --mode homologacao",
1 curtida

Agora deu este erro

$ npm run build --mode homologacao

quizme@0.0.1 build
tsc && vite build --mode homologacao homologacao
src/main.ts(1,17): error TS2307: Cannot find module ‘./App.vue’ or its corresponding type declarations.
src/router/MainRoutes.ts(7,27): error TS2307: Cannot find module ‘@/layouts/full/FullLayout.vue’ or its corresponding type declarations.
src/router/MainRoutes.ts(16,31): error TS2307: Cannot find module ‘@/views/dashboards/Analytical.vue’ or its corresponding type declarations.
src/router/MainRoutes.ts(21,31): error TS2307: Cannot find module ‘@/views/apps/analise-tema/AnaliseTema.vue’ or its corresponding type declarations.
src/router/MainRoutes.ts(26,31): error TS2307: Cannot find module ‘@/views/apps/analise-tema/AnaliseTemaPorId.vue’ or its corresponding type declarations.
src/router/MainRoutes.ts(31,31): error TS2307: Cannot find module ‘@/views/apps/tema/Tema.vue’ or its corresponding type declarations.
src/router/MainRoutes.ts(36,31): error TS2307: Cannot find module ‘@/views/apps/tema/TemaPorId.vue’ or its corresponding type declarations.
src/router/MainRoutes.ts(41,31): error TS2307: Cannot find module ‘@/views/apps/tema/Tema.vue’ or its corresponding type declarations.
src/router/index.ts(10,31): error TS2307: Cannot find module ‘@/views/authentication/Error.vue’ or its corresponding type declarations.
Cleaning up project directory and file based variables
00:01
ERROR: Job failed: exit code 1

Rodou local e o mesmo erro

vi que em todos os arquivos .ts ele criou um arquivo com o mesmo nome com a extensão .js

Parece q foram dois homologação. Mostr seu Vite config. Pq esses js q foram criados, eram pra ir pra pasta build/dist.

Deleta esses js primeiro, pode dar um git stash

1 curtida

Referente a esse erro, vai na pasta @types/index.d.ts e cola isso

declare module '*.vue';
1 curtida