Erros no npm run build no projeto vue - resolvido

34 respostas Resolvido
G

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 ?

34 Respostas

R

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';
G

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 ?

R

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

G

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);
  }
};
G

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
R

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

G

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
R

vc tem um .html nos seus arquivos?

G

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>
R

mostra a estrutura dos arquivos

G

R

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

G

image

image

R

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

R

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",
G

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

G

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

R

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

R

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

declare module '*.vue';
G

vite.config.ts

import vue from "@vitejs/plugin-vue";
import { fileURLToPath, URL } from "url";
import { defineConfig } from "vite";
import vuetify from "vite-plugin-vuetify";

export default defineConfig({
  plugins: [
    vue(),
    vuetify({
      autoImport: true,
      styles: { configFile: "src/scss/variables.scss" },
    }),
  ],
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
    },
  },
  define: {
    'process.env': {}
  },
  css: {
    preprocessorOptions: {
      scss: {},
    },
  },
  optimizeDeps: {
    exclude: ["vuetify"],
    entries: ["./src/**/*.vue"],
  },
});
G

Local não deu erro, mas continuou gerando os .js

Não vou testar no servidor ainda, por causa destes arquivos .js, que estão sendo gerados desta forma

G

Local gerou a pasta dist

G

Alguma novidade ?

R

calmaí pô, eu trabalho kk


vai no seu package.json e muda seu scripts.build pra isso:

"build": "vue-tsc && vite build",
G

Eu sei kkkkkk
Desculpa ai.
vou testar

G

Agora build fica parado neste erro

G

Resolvido.

Este erro era poque tinhas uns console.log

R

Mas cê nem mudou o build, parou de criar os arquivos em js?

Eu ainda tô encucado como “vite homologacao” funciona kkkkkk

G

No arquivo tsconfig.json, inclui “outDir”: “dist”, ai gerou os arquivos .js no local correto

Estava assim:

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

Ficando assim:

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

Vendo aqui na verdade o vite homologacao, não funcionou.
O que funcionou foi o npm run build, com o .env para os endereços corretos.

Estou avaliando novamente

G

Gerei local e agora funcionou. O comando local foi npm run homologacao.

no arquivo .env.homologacao, endereços corretos

VITE_APP_BACKEND_URL=https://xxxxx:8443
VITE_APP_SOCK_URL=wss://xxxxx:8443/socket
VITE_APP_KEYCLOAK_URL=https://xxxxx:8443/

.env.production e .env

VITE_APP_BACKEND_URL=
VITE_APP_SOCK_URL=
VITE_APP_KEYCLOAK_URL=

.env.development

VITE_APP_BACKEND_URL=http://127.0.0.1:8002
VITE_APP_SOCK_URL=wss://localhost:8080/socket
VITE_APP_KEYCLOAK_URL=http://localhost:8080/

package.json

"scripts": {
    "dev": "vite --port 8081",
    "build": "vue-tsc --noEmit && vite build",
    "homologacao": "vue-tsc --noEmit && vite build --mode homologacao",
    "preview": "vite preview --port 5050",
    "typecheck": "vue-tsc --noEmit",
    "lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path .gitignore"
  },

Peguei os arquivos e pastas geradas e coloquei no servidor manualmente e funcionou

G

Ai no .gitlab-ci.yml
fiz assim:

stages:
  - install
  - deploy

install_and_build:
  image: node:16
  stage: install
  cache:
    paths:
      - node_modules/
  only:
    - homologacao
  script:
    - node -v
    #- rm ./package-lock.json
    - npm install
    - npm run homologacao
    - ls
  artifacts:
    paths:
      - dist/

deploy:
  stage: deploy
  only:
    - homologacao
  before_script:
    - apt-get update -qq && apt-get install -y -qq sshpass && apt-get install zip unzip -y
    - zip -r dist.zip dist
  script:
    - sshpass -V
    - export SSHPASS=$CI_USER_PASS
    - sshpass -e scp -o StrictHostKeyChecking=no dist.zip gitlab-ci@$HOST_IP_APP_HOM:/home/gitlab-ci/frontend/
    - sshpass -e ssh -tt -o StrictHostKeyChecking=no gitlab-ci@$HOST_IP_APP_HOM sudo unzip -o /home/gitlab-ci/frontend/dist.zip
    - sshpass -e ssh -tt -o StrictHostKeyChecking=no gitlab-ci@$HOST_IP_APP_HOM sudo rm -rf /var/www/html/*
    - sshpass -e ssh -tt -o StrictHostKeyChecking=no gitlab-ci@$HOST_IP_APP_HOM sudo mv dist/* /var/www/html/
    - sshpass -e ssh -tt -o StrictHostKeyChecking=no gitlab-ci@$HOST_IP_APP_HOM sudo systemctl restart apache2
G
Solucao aceita

solução

R

só lembrando que o .env não interfere em nada no build.


mas vc disse q a dist já tava sendo gerada antes. E aqueles .js estavam sendo gerados pq o build tava só “tsc” e não “vue-tsc”.


show q deu certo

Criado 21 de outubro de 2023
Ultima resposta 26 de out. de 2023
Respostas 34
Participantes 2