What leads to the inability to utilize environment variables in this TypeScript app built with Vue 3?

Currently, I am developing a single page application utilizing Vue 3 and TypeScript. The main purpose of this app is to interact with an API. All the necessary information including the API's URL and key are stored in the 'src\env.js' file:

export default {
 api_url: "https://api.themoviedb.org/3/movie/550?",
 api_key: "somerandomkey"
}

Within the 'src\views\HomeView.vue' file, my code structure looks like this:

<template>
<div class="container">
    <h1 class="page-title">{{ pageTitle }}</h1>
    <MoviesList />
</div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import axios from 'axios';
import env from '@/env.js'
import MoviesList from '../components/MoviesList.vue';

export default defineComponent({
    name: 'HomeView',

    components: {
      MoviesList
    },

    data() {
      return {
        pageTitle: "Popular Movies",
        movies: [],
      }
    },
    methods: {
      getMovies() {
        axios.get(`${env.api_url}api_key=${env.api_key}`).then(response => {
        this.movies = response.data.results;
        })
        console.log(this.movies)
      }
    }
});
</script>

An Issue Arises

Upon compilation, an error message is displayed in the terminal:

Could not find a declaration file for module '@/env.js'.

Seeking Clarifications

  1. What could be causing this complication?
  2. How can this issue be effectively resolved?

Answer №1

It seems that the use of the @ symbol signifies the src folder to your builder and the file is located there.

The error being displayed is due to TypeScript not recognizing the types when you import a .js file.

I suggest two possible solutions:

  • Rename src/env.js to src/env.ts - this will make it a TypeScript file, allowing TS to automatically infer the types
  • If renaming the file is not an option, create a declaration file (env.d.ts) where you manually define the types for the module exports:
export default {
  api_url: string,
  api_key: string
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Building a VueJS custom directive that emits an event

Is it possible to trigger an event from a custom directive using $emit? directive.js: vnode.context.$emit("myEvent") // no luck vnode.child.$emit("myEvent") // error vnode.parent.$emit("myEvent") // error component.vue: <div v-directive.modifier= ...

Building an array from scratch in Angular

Below is the URL to access the code: https://stackblitz.com/edit/ng-zorro-antd-start-xz4c93 Inquiring about creating a new array. For example, upon clicking the submit button, the desired output should resemble the following structure: "tasks": [ { ...

Exploring the Material Drawer functionality within an Angular application

I'm having trouble integrating the Material Drawer component into my Angular app. Despite following the instructions on https://material.io/develop/web/components/drawers/, it's not rendering properly. Could someone please provide a detailed, s ...

Group an object by its name using Java Script/Vue.Js

I am looking to group objects by partial name and assign them to variables data = { SCHOOL-ADMISSION_YEAR: "2021" SCHOOL-SCHOOL_NAME: "ABC SCHOOL" SCHOOL-SCHOOL_LOCATION: "NEWYORK" ENROLLMENT-ADMISSION_YEAR: " ...

Using Typescript and react-redux with a Stateful Component: The parameter type 'typeof MyClass' does not match the expected component type

I've been trying to dive into the world of Typescript, React, and Redux. However, I've hit a roadblock at the moment. This is the error I encountered: ./src/containers/Hello.tsx [tsl] ERROR in /home/marc/Development/TypeScript-React-Starte ...

When the React Native Expo app is running, the TextInput form is covered by the keyboard

When I launch the app using expo and implement my DateFormInput component, the issue of Keyboard covering TextInput arises. Despite trying packages like "@pietile-native-kit/keyboard-aware-scrollview", "@types/react-native-keyboard-spacer", "react-native-k ...

Tips for transforming a Json array into an object in Angular 5

I am working with a Json array that looks like this: [{"name":"ip","children":{"label":"ip","value":"","type":"text","validation":"{ required: true}"}} ,{"name":"test","children":{"label":"test","value":"","type":"text","validation":"{ required: true}"}} ...

What is the reason behind the lack of exported interfaces in the redux-form typings?

I've been exploring how to create custom input fields for redux-form. My journey began by examining the Material UI example found in the documentation here. const renderTextField = ({input, label, meta: { touched, error }, ...custom }) => < ...

Executing cypress tests with tags in nrwl nx workspace: A simple guide

Currently, I am working within a nrwl nx workspace where I have set up a cypress BDD cucumber project. My goal is to run cypress tests based on tags using nrwl. In the past, I would typically use the "cypress-tags" command to achieve this. For example: &q ...

What are the steps to integrate video recording functionality from Agora into a Vuejs application?

Currently, I am working on a project that utilizes Vuejs for the frontend and Django for the backend. As part of this project, I have successfully integrated Agora-Web-SDK-NG for video calls. However, I am now looking to implement a feature that involves ...

Tips for integrating Paged.js with Vue.js2:

const newPreview = new Preview(); newPreview.preview('example', \[\], document.body).then((result) => { console.log("Rendered successfully", result.total, "pages."); }); Encountering the following issue: 1:1188-1197 'Previewer ...

Having difficulty retrieving values while using async-await

Utilizing the code below has been successful for me. I managed to retrieve the data in the spread (then), returning a http200 response. Promise.all([ axios({ method: 'post', url: 'https://oauth2.-arch.mand.com/oauth2/token&a ...

Updating meta tags dynamically in Angular Universal with content changes

Hello, I'm encountering an issue with a dynamic blog page. I am trying to update meta tags using data fetched from the page. Here's the code snippet: getBlogPost() { this.http.get(...) .subscribe(result => { this.blogPost = re ...

Is Babel necessary for enabling JavaScript compatibility in my TypeScript React project, excluding Create React App?

This is the webpack configuration for my React project built in TypeScript, module.exports = { mode: 'development', entry: ['./src/main.tsx'], module: { rules: [ { // Rule for ts/tsx files only, no rule for js/js ...

Leveraging a single Axios request across various components

My current setup involves making a simple Axios call in this way: .get('https://myAPI.com/') .then(response => { this.info = response.data }) Subsequently, I utilize a v-for array loop on my components to display the retrieved data. ...

What is the approach to forming a Promise in TypeScript by employing a union type?

Thank you in advance for your help. I am new to TypeScript and I have encountered an issue with a piece of code. I am attempting to wrap a union type into a Promise and return it, but I am unsure how to do it correctly. export interface Bar { foo: number ...

Deactivating Bootstrap Modal in Angular

Looking for advice on managing a Bootstrap Modal in Angular 7 I have a Form inside a Bootstrap Modal that I need to reset when the modal is closed (by clicking outside of it). Despite searching on Google, I haven't been able to find a solution. Any ...

What is the best way to extract and display data from an API response object in my

{ "_metadata": { "uid": "someuid" }, "reference": [ { "locale": "en-us", ... bunch of similar key:value "close_icon_size" ...

Parentheses are automatically wrapped around the implicit return of arrow functions

Currently, I am utilizing Visual Studio Code along with Prettier, and I have noticed that the function: (token: string) => this.token = token is being transformed into: (token: string) => (this.token = token) This modification seems to decrease r ...

What is the best method to extract the values of objects in an array that share

var data= [{tharea: "Rare Disease", value: 3405220}, {tharea: "Rare Disease", value: 1108620}, {tharea: "Rare Disease", value: 9964980}, {tharea: "Rare Disease", value: 3881360}, ...