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.