Using Vite with a Chrome Extension Manifest version 3 throws the error "Import statement can only be used inside a module" when attempting to use inpage scripts

I recently developed a browser extension using the foundation of https://github.com/Jonghakseo/chrome-extension-boilerplate-react-vite project. Within the manifest file, I specified the background type as module

 background: {
    service_worker: "background.js",
    type: "module",
  },

In the background service, I dynamicallly generate inpage content-scripts like this

 await chrome.scripting.registerContentScripts([
      {
        id: currInpageId,
        matches: ["file://*/*", "http://*/*", "https://*/*"],
        js: [`inpage-${inpageType}.js`],
        runAt: "document_start",
        allFrames: true,
        world: "MAIN",
      },
    ]);

The inpage files are provided as individual inputs in the vite.config file

input: {
          ...inpageTypes.reduce(
            (acc, inpageType) => ({
              ...acc,
              [`inpage-${inpageType}`]: resolve(
                inpageDir,
                `inpage-${inpageType}.ts`
              ),
            }),
            {}
          ),
        },

However, upon running the extension, I encounter an error

Uncaught SyntaxError: Cannot use import statement outside a module

What steps can I take to resolve this issue?

Appreciate any assistance!

Answer №1

Following the advice of @wOxxOm, I divided my Vite configuration into three separate parts:

  • In-page configuration
  • Content script configuration
  • Remaining code configuration

For the in-page and content-script configurations, I included:

build: {
  emptyOutDir: false,
  ...
  rollupOptions: {
    output: {
      entryFileNames: "[name].js",
      inlineDynamicImports: true,
    }
  }
}

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

When comparing TypeScript index signatures to Record<Keys, Type> return type, the focus is on handling objects with unspecified properties

I have a function called getQueryParams that takes a string as input and returns an object with unknown properties: function getQueryParams(s) { if (!s || typeof s !== 'string' || s.length < 2) { return {} } return s .substr(1) ...

Attempting to utilize a namespace-style import for calling or constructing purposes will result in a runtime failure

Using TypeScript 2.7.2 and VSCode version 1.21 with @types/express, I encountered an issue where in certain cases VSCode would report errors like: A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Interestingly ...

When compiling in Visual Studio 2019, the process terminated with exit code -1073741819

Today, upon returning to my asp .net core-project with react and typescript as front end, I encountered an error message after running the "Build" command. Can anyone shed some light on what this error means and how it can be fixed? Severity Code De ...

The i18next module encounters compilation issues when used in a React application with Typescript

In my React-Typescript project, I recently set up i18next for multi-language support. Despite following the official documentation guidelines, I encountered compilation errors when running the app: Property 'changeLanguage' does not exist on type ...

Building a custom CellRenderer in AGGrid using TypeScript within a React environment

Currently, I am utilizing React along with TypeScript and attempting to create a custom CellRenderer in AGGrid. My code is structured like this: PriorityCellRenderer.tsx import React from 'react'; function PriorityCellRenderer(props:any) { co ...

Error TS2694 occurs in React when the namespace 'React' does not have an exported member. This issue typically arises when there is

Currently, I am attempting to incorporate the antd library into a React project that was created using Visual Studio 2017 (15.2.2). To start, I utilized the "ASP.NET Core Web Application" project template and selected "React.js" in the dialog below. http ...

What is the best way to determine if a value from my array is present within a different object?

I have an array with oid and name data that I need to compare against an object to see if the oid value exists within it. Here is the array: const values = [ { "oid": "nbfwm6zz3d3s00", "name": "" ...

How can you ensure a code snippet in JavaScript runs only a single time?

I have a scenario where I need to dynamically save my .env content from the AWS secrets manager, but I only want to do this once when the server starts. What would be the best approach for this situation? My project is utilizing TypeScript: getSecrets(&qu ...

What is the best way to determine the property type dynamically in TypeScript based on the value of another property?

I have been working with Polymorphic relationships and currently have the following TypeScript interface defined: interface SubjectA {} interface SubjectB {} interface SubjectC {} enum SubjectType { SubjectA = 'Subject A', SubjectB = 'S ...

What is the best way to design a circular icon using OpenLayers?

I am currently incorporating openlayers into my ionic app and working on placing users on the map. I have encountered a problem as I am unsure how to apply custom CSS styling to the user element, which is not directly present in the HTML. In the screenshot ...

Guide on leveraging the `ConstructorParameter` tool with generic-friendly types

Attempting to extract the constructor parameter type from a class, but the class in question accepts a generic type value. Does anyone know how to achieve this? Encountered error: ConstructorParameters<typeof(DictionaryClass<contentType>)[0]; ...

Prisma: choose from numerous options in a many-to-many relationship with various criteria

I have a unique scenario with two tables, User and Post, that are connected through a custom many-to-many table: model User { id Int @id @default(autoincrement()) name String enabled Bool posts users_to_posts[ ...

zod - Mastering the Art of Dive Picking

Working with zod and fastify, my UserModel includes the username and device properties. The username is a string, while the device consists of "name", "id", and "verified" fields in an object (DeviceModel). For the sign-up process, I need to return the co ...

Having trouble pinpointing the specific custom exception type when using the throw statement in TypeScript?

I have run into a problem while using a customized HttpException class in TypeScript. Let me show you how the class is structured: class HttpException extends Error { public status: number | undefined; public message: string; public data: any; ...

Using Typescript Type Guard will not modify the variable type if it is set in an indirect manner

TL;DR Differentiation between link1 (Operational) vs link2 (not functional) TypeGuard function validateAllProperties<T>(obj: any, props: (keyof T)[]): obj is T { return props.every((prop) => obj.hasOwnProperty(prop)) } Consider a variable ms ...

The argument '$0' provided for the pipe 'CurrencyPipe' is not valid

When retrieving data from the backend, I receive $0, but I need to display it as $0.00 in my user interface. <span [innerHTML]="session.balance | currency :'USD': true:'1.2-2'"></span> I'm encountering an issue where ...

Incorporating Google Pay functionality within Angular applications

I have been attempting to incorporate Google Pay into my Angular project, but I am struggling to find reliable resources. My main issue revolves around the following code... <script async src="https://pay.google.com/gp/p/js/pay.js" onloa ...

I'm looking for the Type Definitions Files (*.d.ts) for the Amazon Cognito Identity SDK. Does anyone know where I can find them and how

Where can I locate Type Definitions Files (*.d.ts) for the Amazon Cognito Identity SDK and how can I use them? I am utilizing TypeScript for Angular2 and I would like to have the code assistant readily available when implementing "AWS Cognito." While I al ...

Using routing with modules instead of components in Angular 10+ involves configuring the routing paths within the module files

I recently tried implementing modules instead of components for routing in Angular 10, but encountered a white screen issue. Any assistance would be greatly appreciated. Here is the code snippet I've been working with: import { NgModule } from &apos ...

Using HttpParams to make a GET request in Angular

Here is the GET mapping in my backend: @GetMapping(value = "search") public List<Cat> search(@RequestBody CatDto catDto) { return catService.search(catDto); } I am trying to send a GET request to retrieve a list using Angular's HttpClient ...