Error: Unable to locate the reference for "foo" while utilizing TypeScript in combination with Webpack

My Chrome extension is functioning properly when using JavaScript alone.

However, when attempting to incorporate TypeScript with Webpack, I encountered an issue where the function foo could not be found.

Uncaught ReferenceError: foo is not defined

Here is a snippet from my manifest.json:


    "content_scripts":
    [
        {
            "js": ["global.js", "content.js"],
            "matches": ["https://*.my-domain.com/*"],
            "run_at": "document_end"
        }
    ],

Within content.ts :

console.log("content.js");

let afterDOMLoaded = () =>
{
    foo()
    .then((result) => console.log(result))
    .catch((error) => console.error(error));
}

if (document.readyState === 'loading')
{
    document.addEventListener('DOMContentLoaded', afterDOMLoaded);
}
else
{
    afterDOMLoaded();
}

In global.js :

console.log("global.js");

let foo = async () =>
{
    await something();
}

I've also included a tsconfig.json file and webpack.config.js in my project setup. However, despite following the correct script loading order as indicated by console.log output:

global.js
content.js

The issue persists that if I define foo right at the top of content.ts, everything works seamlessly.

At this point, it's unclear whether the problem lies within webpack or TypeScript. Any insights would be greatly appreciated.

Answer №1

Webpack encapsulates each "module" (where a file serves as its own module) within its own function scope, ensuring that the variable let foo is restricted to block scope and cannot be accessed globally by other modules like content.

To resolve this, consider utilizing the export/import syntax provided by webpack, or opt for placing it in global scope (without using any variable keyword). Keep in mind that setting variables in global scope within an extension might cause conflicts with the content of web pages being rendered.

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

Enhancing Test Components with Providers in "React Testing Library": A Step-by-Step Guide

I am currently working with React-Testing-Library and have set up my main.tsx file with Redux-Toolkit and React-Router wrappers like this: ReactDOM.createRoot(document.getElementById("root")!).render( <React.StrictMode> <Provider s ...

Locate and embed within a sophisticated JSON structure

I have an object structured as follows: interface Employee { id: number; name: string; parentid: number; level: string; children?: Employee[]; } const Data: Employee[] = [ { id:1, name: 'name1', parentid:0, level: 'L1', children: [ ...

Updating the state in React is causing significant delays

In my React project, I am utilizing the pdf-lib (JS library) for some intensive tasks using async/await. My goal is to update a progress bar by modifying the state. However, when I use setState within a setTimeout, the state changes are not reflected unt ...

What steps should I take to address the numerous errors I am encountering in Atom using the Atom linter tool?

My Atom interface is showing the following errors: {Error running gjslint}(x4) {Error running selective}(x4) Upon checking the errors section, I found the following details: [Linter] Error running selective Error: ENOENT: no such file or directory, open ...

Using JavaScript to place a particular tag at a designated position

I have a string that looks like this: var txtstr='<p>Text 1</p><p>&nbsp;</p><p>Text &nbsp;2</p><p>&nbsp;</p><p>Text 3&nbsp;</p>'; I have an <img src=..../> tag and ...

Tips for updating parameters that are defined in a controller within a promise

Currently, I am developing a single page application using Angular and TypeScript. I am facing an issue with updating the parameter value (_isShowFirst) of the controller inside a promise function. It seems like nothing is recognized within the promise blo ...

Using Required and Partial with an Array of Generic Types

I'm currently working with the following types: interface Color { color: string } type DarkerColor<T> = T & Color & { darker: string } type ColorInfo<T> = DarkerColor<T> & { hue: number luminance: number opacity ...

Exploring the Concept of Template Element Recursion in Angular JS 2

In my Angular 2 project, I encountered a situation where I needed to iterate through ngFor based on child elements. My component should be able to render a list based on the input provided. Here is an example of the data structure: [ { name: 'ABC ...

When attempting to utilize class validators in NestJS, Param is refusing to cast to DTO type

I'm currently working on implementing validation for the parameter I receive in a request, especially when trying to delete something. The parameter is expected to be a string but it must adhere to the format of a valid UUID. To achieve this, I have i ...

When a variable is used in Postgresql, the ORDER BY clause is disregarded, but accurate results are returned when the variable value is

After investigating, it seems that the query is always returning rows ordered by id, regardless of the value passed in the sortType variable (verified in console). export async function fetchAnimalList(sortType) { noStore(); try { const areas = aw ...

Creating encoded objects for a content-type of `application/x-www-form-urlencoded`

Upgrading AngularJS Code to Angular 2+ - Http Issue I am in the process of converting some legacy AngularJS code (specifically Ionic 1) to the latest version of Angular (Ionic 4), and I've encountered a troubling issue. Previously, in every HTTP POS ...

Leverage generic types and allow acceptance of objects with arbitrary keys

Is it possible to allow the Use function argument type to accept any unknown key, as well as correctly type the keys from SomeGeneric? function Example (opt: { valid?: boolean }) { } type SomeGeneric = Parameters<typeof Example>[0] function Use(op ...

Tips for obtaining the OneSignal playerID

When launching the app, I need to store the playerID once the user accepts notifications. This functionality is located within the initializeApp function in the app.component.ts file. While I am able to retrieve the playerID (verified through console.log) ...

Find all documents in Angular Firestore that are related to a specific document_REFERENCE

Seeking a way to search through all documents in collection a that have a reference to a specific document in collection b. Despite my efforts, I couldn't find a solution here or on Google :/ This is what I tried in my service class: getAsFromB(id ...

Encountering issues with MediaSession.setPositionState() and seekto functionalities not functioning properly

Having trouble with MediaSession.setPositionState() not displaying the audio time and seekbar not behaving as expected. const sound= document.querySelector('sound'); function updatePositionState() { if ('setPositionState' in navigato ...

"Error 404: The file you are looking for cannot be found on [custom company domain]. Please check

My attempts to retrieve a Google Drive file using its file ID with a service account in NodeJS have been unsuccessful. The requests are failing with an error indicating a lack of access: code: 404, errors: [ { message: 'File not found: X ...

Tips for properly narrowing a function parameter that includes "an object key or a function"

Working on a function to retrieve a property using either a string key or a callback, I've encountered an issue with TypeScript narrowing the type parameter. Here is the function in question: function get<T, V>(value: T, fn: (value: T) => V) ...

Type Assertion for Optional Values in TypeScript

Just confirming the proper way to handle situations like this. My current setup involves using Vue front-end with Typescript, sending data to an API via axios. I've defined reactive objects as follows: const payload = reactive({ name: '' ...

The specified 'Object' type does not match the required 'Document' constraint

I need assistance with running a MERN application to check for any issues, but I keep encountering this error across multiple files. Error: The 'CatalogType' type does not meet the requirements of 'Document'. The 'CatalogType&apo ...

The slice() method in arrays provides a reference to the elements rather than copying

In my file, I am exporting an object in the following manner: export const LINECHART2_DATA = { series: [{ data: [], name: 'HR', }, { etc... }] } The way I import it is like this: import { LINECHART2_DAT ...