Steps for setting up tsconfig.json for Chrome extension development in order to utilize modules:

While working on a Chrome plugin in VS Code using TypeScript, I encountered an issue with the size of my primary .ts file. To address this, I decided to refactor some code into a separate module called common.ts.

In common.ts, I moved over certain constants and functions like so:

export function doSomething(foo : string): string { ... }

To access these exports from my main .ts file, I used qualified references, for example:

let result = common.doSomething("foo");

Despite being able to import the code successfully with:

import common = require("./common");

Upon launching my extension, however, I encountered the following error:

Uncaught ReferenceError: define is not defined at popup.ts:2

This error seemed to be related to this portion of the generated JavaScript:

define(["require", "exports", "./common"], function (require, exports, common) {

In my tsconfig.json, my settings are currently as follows:

{
    "compilerOptions": {
        "target": "es6",
        "module": "amd",
        "sourceMap": true
    }
}

I even attempted switching to the "commonjs" module, but encountered a similar issue with "exports" not being defined:

Object.defineProperty(exports, "__esModule", { value: true });

Venturing into the "system" module resulted in the same problem, where "System" was not recognized:

System.register(["./common"], function (exports_1, context_1) {

Exploring the "es2015" module led me to import using

import * as common from "./common";
, which caused Chrome to flag an error:

Uncaught SyntaxError: Unexpected token *

I also experimented with changing the target in tsconfig.json and using different patterns for importing like

import { doSomething } from "./common"
.

What steps should I take to properly configure tsconfig.json, structure the module (note that I do not use the module or namespace keywords in common.ts), and correctly import the module so I can streamline my code and utilize it in a browser?

Answer №1

After conducting some brief research (not having personal experience in developing Chrome extensions), it appears that there are two main approaches you can take:

  1. Utilize a bundler like Webpack to convert one of TypeScript's supported "module" output formats into a single JavaScript file, or

  2. Specify "module": "es2015" and employ an HTML page to load your modules into Chrome, as outlined here or here.

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

A guide on organizing similar elements within an array using Angular

Could you assist me in grouping duplicate elements into separate arrays of objects? For example: array = [{key: 1}, {key: 5}, {key: 1}, {key: 3}, {key: 5}, {key: 1}, {key: 3}, {key: 2}, {key: 1}, {key: 4}]; Expected output: newArrayObj = {[{key: 1}, {key ...

Having trouble getting @types/express-session to function properly. Any suggestions on how to fix it?

My web-app backend is built with TypeScript and I've integrated express-session. Despite having @types/express and @types/express-session, I continue to encounter type errors that say: Property 'session' does not exist on type 'Request ...

ERROR: The variable countryCallingCode has not been defined

I encountered an error when attempting to assign a value to my property countryCallingCode, which does not exist in the first option. this.allData.customerFacingPhone.countryCallingCode = newItem.countryCallingCode The error message I received was: ERROR ...

Exploring i18nNext integration with antd table in React

Presently, this is the UI https://i.stack.imgur.com/CMvle.png App.tsx import "./styles.css"; import MyTable from "./MyTable"; export default function App() { const data = [ { key: "1", date: "2022-01- ...

Identified the category

How can I retrieve the default option from a list of options? type export type Unpacked<T> = T extends Array<infer U> ? U : T; interface getDefaultValue?: <T extends Option[]>(options: T) => Unpacked<T>; Example const options = ...

Vite encounters issues when using PNPM because of import analysis on the `node_modules/.pnpm` package

When utilizing PNPM and Vite in a monorepo, I encountered a perplexing issue. The email addresses appearing like `<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0b6a9b4a580f4eef4eef9">[email protected]</a>_@<a ...

Unlock the full potential of working with TaskEither by utilizing its powerful functionality in wrapping an Option with

After exploring various examples of using TaskEither for tasks like making HTTP requests or reading files, I am now attempting to simulate the process of retrieving an item from a database by its ID. The possible outcomes of this operation could be: The i ...

What is the best way to securely store a sensitive Stripe key variable in an Angular application?

When implementing Stripe payment system in my Angular App, I often wonder about the security of storing the key directly in the code as shown below. Is this method secure enough or should I consider a more robust approach? var handler = (<any>windo ...

Struggling to navigate through rows in a Material UI Table

After performing a search in my TextField, the rows appear correctly in the console. However, the table itself does not update at all. I attempted to set the result of the search to a new array, but this made my TextField read-only. Any assistance with fur ...

Designing a platform for dynamic components in react-native - the ultimate wrapper for all elements

export interface IWEProps { accessibilityLabel: string; onPress?: ((status: string | undefined) => void) | undefined; localePrefix: string; children: JSX.Element[]; style: IWEStyle; type?: string; } class WrappingElement extends React.Pure ...

Unable to create a loop within the constructor to assign API values

I created an export type shown below: export type Program{ key: string; value: string; } An array of values is returned from the API like this: apival = ["abc", "xyz" ...etc] In my component's constructor, I am implementing the f ...

injecting a variable from the configuration service into a TypeScript decorator

I am interested in setting up a scheduled task for my NestJs application to run at regular intervals. I found information on how to use intervals in the NestJs documentation. Since my application uses configuration files, I want to keep the interval value ...

Navigating with Angular: Every time I refresh the page or enter a specific URL, Angular automatically redirects to the parent route

In my CRM module, I have created a custom Routing Module like this: const routes: Routes = [ { path: 'crm', component: CrmComponent, children: [ { path: '', redirectTo: 'companies', pathMatch: 'full&ap ...

What is the process for combining an object and a primitive type to create a union type?

Having a tricky time with Typescript and finding the correct typing for my variable. What seems to be the issue? The variable selected in my code can either be of type DistanceSplit or number. I have an array that looks like this: [-100, DistanceSplit, D ...

What is the best way to create an instance method in a subclass that can also call a different instance method?

In our programming project, we have a hierarchy of classes where some classes inherit from a base class. Our goal is to create an instance method that is strongly-typed in such a way that it only accepts the name of another instance method as input. We d ...

There seems to be an issue with the Typescript version compatibility in the node_modules folder for the Angular Material table cell component

While working on my project with Angular, I encountered an issue. I attempted to downgrade my TypeScript version to 3.9.7 but the problem persists. Below are the dependencies listed in my package.json: "private": true, "dependencies&qu ...

Having Trouble with Imported JavaScript File in Astro

Why isn't the js file working in Astro when I try to import or add a source in the Astro file? For example: <script src="../scripts/local.js"></script> or <script>import '../scripts/local.js'</script> I am ...

Is there a way to combine compiling TypeScript and running the resulting .js file into one build command in Sublime Text 3?

I have successfully installed the TypeScript plugin on Sublime Text 3. Once installed, a build system is added to the menu for easy access. https://i.stack.imgur.com/m21bT.png You can simply press "Command + B" to build a .ts file. My goal is to compile ...

What is the best way to dynamically disable choices in mat-select depending on the option chosen?

I was recently working on a project that involved using mat-select elements. In this project, I encountered a specific requirement where I needed to achieve the following two tasks: When the 'all' option is selected in either of the mat-select e ...

Puppeteer: What is the best way to interact with a button that has a specific label?

When trying to click on a button with a specific label, I use the following code: const button = await this.page.$$eval('button', (elms: Element[], label: string) => { const el: Element = elms.find((el: Element) => el.textContent === l ...