Issue with importing and exporting external types causing failures in Jest unit tests for Vue 2

I am in the process of creating a package that will contain various types, enums, consts, and interfaces that I frequently use across different projects.

To achieve this, I have set up a main.ts file where I have consolidated all the exports and specified it in the package.json:

"main": "main.ts"
.

One of the exports requires some types from mapbox-gl. However, I do not want to include the entire mapbox-gl library in my package. To address this, I took the following approach:

"peerDependencies": {
  "mapbox-gl": "^1.13.0"
},
"devDependencies": {
  "@types/mapbox-gl": "^1.13.0",
}

Within the main.ts file, I have included the following:

import mapboxgl from "mapbox-gl";

export interface DataSourceOptions {
  shouldLoad?: boolean;
  name: string;
  map: mapboxgl.Map;
  layer: mapboxgl.Layer;
}

After publishing my package, I imported it into my project and everything worked smoothly until I tried testing components using this package.

Jest started throwing an error stating:

D:\path\to\project\node_modules\some-custom-package\main.ts:1 ({"Object.":function(module,exports,require,__dirname,__filename,global,jest){import mapboxgl from "mapbox-gl"; SyntaxError: Cannot use import statement outside a module

In an attempt to resolve this issue, I added my package to the transformIgnorePatterns in the jest.config.js:

transformIgnorePatterns: [
  "<rootDir>/node_modules/(?!(@mapbox/mapbox-gl-draw" +
    "|some-custom-package" +
    ")/)",
],

However, the error persisted.

I also tried bundling my package with rollup, utilizing both tsc and rollup-plugin-typescript2 plugins as I know that in rollup I can specify externals to declare mapbox-gl accordingly. Unfortunately, neither tsc nor rollup-plugin-typescript2 seemed to recognize my interfaces, only the constants, types, and enums (possibly related).

While it may seem like multiple questions bundled into one, I am solely seeking out a solution.

  • Resolve Jest's importing problem (as it works fine within the app but fails during tests)
  • Find a way to retain interfaces while bundling the exports with rollup and declaring mapbox-gl as external

A potential workaround could involve avoiding the direct import of mapboxgl in my package by making the types used from it dynamic:

export interface DataSourceOptions<M,L> {
  shouldLoad?: boolean;
  name: string;
  map: M;
  layer: L;
}

This would allow me to specify in my project:

options: DataSourceOptions<mapboxgl.Map, mapboxgl.Layer>
. However, I am not particularly fond of this solution as it sidesteps the issue rather than solving it.

Answer №1

After some troubleshooting, I managed to resolve the issue by including:

"type": "module"

within the modules' package.json, and also adding it to transformIgnorePatterns in the jest.config.js file of the project that utilizes it, as depicted above.

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

Guide to displaying options in the Vue material select box even when the default value is blank

I have implemented the material design framework vuematerial with vue.js. In traditional HTML, a selection box looks like this: <select> <option value="">You should initially see this</option> <option value="1">One</o ...

Unable to combine mui theme with emotion css prop

I recently made the switch from overwriting styles in my styles.css file with !important to using emotion css prop for implementing a dark theme in my web app. Below is the code snippet from App.tsx where I define my theme and utilize ThemeProvider: const ...

Unlinking styles from the template in Vue.js

I have a unique situation where my template contains a <style> block that needs to be positioned near its corresponding div due to CMS restrictions. However, when I try to integrate Vue.js into the mix, it appears to strip out the style block and di ...

Setting up Webpack for react-pdf in a Next.js application

In my Next.js application, I am utilizing the react-pdf library to generate and handle PDF files on the client side without involving the server. However, I am facing challenges in setting up Webpack for Next.js as I lack sufficient expertise in this area. ...

How to send dynamic values to a computed function in Vue.js

Trying to pass an id with the v-model in order to dynamically filter a table without hardcoding names into the function. The goal is for the function to be able to filter both select boxes. The data is referred to as guides, containing attributes such as ...

Can the autoscroll offset be adjusted while dragging?

I am developing a single-page application using Vue.js. The user interface consists of three main components: A fixed navbar at the top with a z-index of 2 A fixed sidebar on the left with a z-index of 1, and padding to accommodate the navbar A central ar ...

How to identify alterations in user input within Angular?

I need assistance with my search input functionality. I want to ensure that the this.searchProperties.emit is only triggered when the user interacts with the input field by touching it or making an input. The current issue is that the emit function gets ca ...

I am facing an issue with updating the mat-table after pushing values to a

I have a uniqueFormGroup with UniqueFormArray and a special-table that displays the array. When I add new uniqueFormGroup to UniqueFormArray, the special-table doesn't add new row. I was attempting to implement trackBy, but I am unsure of where (and ...

Different categories of "areas" found in TypeScript within Visual Studio 2013

In C#, we often use "regions," but unfortunately that feature is missing in TypeScript. Is there a way to group code sections in TypeScript? I came across this article on Stack Overflow discussing the absence of regions in TypeScript. I'm curious if ...

How can Angular CLI prevent the submission of an HTML form unless a previous option has been selected

I am currently working on a form that contains select fields with various options pre-populated. <form [formGroup]="selectVehicleForm"> <select formControlName="Manufacturer"> <option *ngFor='let ...

Utilizing Typescript to retrieve a specific object property using square brackets and a variable

How can we correctly access a JavaScript object in TypeScript using variable evaluation with bracket notation, such as myObject[myVariable], when the value of the variable is unknown initially? In the code below, an error occurs due to the uncertainty of ...

Atom-typescript does not always successfully compile all typescript files to JavaScript

Currently, I am in the process of learning how to implement routing in Angular2 by following a tutorial. The tutorial involves creating partial pages using .ts files along with companion .js files for each page. While my Atom editor, equipped with atom-typ ...

Error encountered in Intellij for Typescript interface: SyntaxError - Unexpected identifier

I am currently testing a basic interface with the following code: interface TestInterface { id: number; text: string; } const testInterfaceImplementation: TestInterface = { id: 1, text: 'sample text' }; console.log(testInterface ...

Tips for shrinking the size of electron applications

After installing my electron application on Mac, I noticed that it is surprisingly large at 1.39GB, while the Windows version is only around 70MB. Upon unpacking the dmg file, I discovered a file named app.asar which accounts for a significant portion of t ...

How can I use a string variable in Angular 2 to create a dynamic template URL

@Component({ selector: 'bancaComponent', templateUrl: '{{str}}' }) export class BancaComponent implements OnInit { str: String; constructor(private http: Http) { } ngOnInit(): void { this.str = "./file.component.html"; } An ...

Serverless-offline is unable to identify the GraphQL handler as a valid function

While attempting to transition my serverless nodejs graphql api to utilize typescript, I encountered an error in which serverless indicated that the graphql handler is not recognized as a function. The following error message was generated: Error: Server ...

Maximizing Jest's potential with multiple presets in a single configuration file/setup

Currently, the project I am working on has Jest configured and testing is functioning correctly. Here is a glimpse of the existing jest.config.js file; const ignores = [...]; const coverageIgnores = [...]; module.exports = { roots: ['<rootDir&g ...

What is the syntax for typing the router instance in Next.js?

I'm working on a password reset request form in my Next.js project. Here's the code I have: "use client"; import * as React from "react"; import { zodResolver } from "@hookform/resolvers/zod"; import { useForm } fro ...

Error TS2403: All variable declarations following the initial declaration must be of the same type in a React project

While developing my application using Reactjs, I encountered an error upon running it. The error message states: Subsequent variable declarations must have the same type. Variable 'WebGL2RenderingContext' must be of type '{ new (): WebGL2 ...

Retrieve the raw text from the input field instead of the date object

Below is the HTML code for an input field: <div class="input-group input-group-md"> <input id="date" name="date" [readOnly]="disabled" type="text" placeholder="M0/d0/0000 Hh:m0:s0" [placeholder]="pl ...