Error: Attempting to reassign a value to an imported module is

I am having an issue with importing a module into a TypeScript file and then bundling it using Rollup.js.

After running tsc without any errors, I encountered an error message when I tried to run:

$ rollup -c rollup.config.js

Illegal reassignment to import 'mapboxgl'
Error: Illegal reassignment to import 'mapboxgl'
...
Type rollup --help for help, or visit https://github.com/rollup/rollup/wiki

The problem seems to arise when this line is present:

(mapboxgl as any).accessToken = this.accessToken;
.

Here is how my rollup.config.js file is configured:

export default {
  moduleName: "mapbox.core",
  entry: 'src/js/index.js',
  format: 'umd',
  dest: 'core/core.umd.js',
  sourceMap: true,
  globals: {
   'mapbox-gl': 'mapboxgl'
  }
};

Answer №1

Although a bit frustrating, I found a workaround to avoid the error and make the mapbox-gl module function properly by utilizing an assign function to set the accessToken on mapboxgl.

I made the following adjustments:

import * as mapboxgl from 'mapbox-gl';

(mapboxgl as any).accessToken = this.accessToken;
this.map = new mapbox.Map({...});

Which I modified to:

import * as mapboxgl from 'mapbox-gl';

this.assign(mapboxgl, "accessToken", this.accessToken);
this.map = new mapboxgl.Map({...});

/*
 *
 * credits to this answer for the assign function:
 * http://stackoverflow.com/a/13719799/2393347
 *
 */
private assign(obj: any, prop: any, value: any) {
    if (typeof prop === "string")
        prop = prop.split(".");

    if (prop.length > 1) {
        var e = prop.shift();
        this.assign(obj[e] =
                Object.prototype.toString.call(obj[e]) === "[object Object]"
                ? obj[e]
                : {},
            prop,
            value);
    } else
        obj[prop[0]] = value;
}

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

The useRef function is malfunctioning and throwing an error: TypeError - attempting to access 'filed2.current.focus' when 'filed2' is null

I'm attempting to switch focus to the next input field whenever the keyboard's next button is pressed. After referring to the react native documentation, it seems that I need to utilize the useRef hook. However, when following the instructions f ...

RxJs: Generating an observable based on changes in a field's value

Is there a way to generate an Observable using the variable this.pending as its source? I'm looking to create an Observable that will produce a new feed each time the value of this.pending changes. For example, if I update this.pending to be false i ...

Is it possible to use Immutable named parameters with defaults in Typescript during compilation?

Here is an example that highlights the question, but unfortunately it does not function as intended: function test({ name = 'Bob', age = 18 }: { readonly name?: string, readonly age?: number }) { // this should result in an error (but doesn&apo ...

Tips for creating parameterized keys for a specific type in Typescript

I've encountered a challenge while transitioning my react-native project from Flow to TypeScript. The stumbling block is recreating this specific type from Flow: declare type ApolloData<T, nodeName: string = 'node'> = { [nodeName]: ...

Encountering an issue with TypeScript and Jest when trying to import a file leads to an

Having trouble with using Jest in a TypeScript environment. //myprovider.tsx class MyProvider{ constructor(){} giveMeFive(): int{ return 5; } } export { MyProvider } // myprovider.test.js import { MyProvider } from './myprovider'; ...

Tips for integrating Appbar and BottomNavigation in React Native Paper

The BottomNavigation is a great choice for mobile navigation, but for the web version, I have a different preference inspired by Instagram: https://i.sstatic.net/9XTlb.png Navbar.tsx: import React from 'react' import {Appbar, BottomNavigation} ...

Does an empty object disrupt type passing in a generic array?

Looking to develop a versatile function that can pick a random element from an array while maintaining type information using Typescript 2.6.2. function sample<T>(array: T[]) : T { const index = Math.floor(Math.random() * array.length); return a ...

Encountering the "Error: data.map is not a function" issue within Next.js

I'm having trouble understanding why this first fetch call works perfectly: async function getData() { const res = await fetch('https://jsonplaceholder.typicode.com/todos') return res.json() } export default async function Home() { co ...

What sets apart calling an async function from within another async function? Are there any distinctions between the two methods?

Consider a scenario where I have a generic function designed to perform an upsert operation in a realmjs database: export const doAddLocalObject = async <T>( name: string, data: T ) => { // The client must provide the id if (!data._id) thr ...

How can I find the name of a function in TypeScript?

Does anyone know how to retrieve the name of a function passed in as a parameter? console.clear(); class A{ test(){ } testCall(fnc:Function){ console.log(fnc.name); // I want it to display 'test' here, not empty console.log( ...

Encountering a TypeScript error in Vue 3 when trying to assign a type of '($event: any) => void' to an event listener

Snippet of component code: <h2 @click="handleEvent(post.id)">{{ post.title }}</h2> function handleEvent(id: number) { router.push("/post/" + id); } Error message in TypeScript: Type '($event: any) => void' i ...

Having difficulty refreshing UI using React useState while trying to update an array of elements

Struggling with updating my UI using React and useState. Any help would be greatly appreciated. I am trying to remove an item that a user added. interface Links { link: string; } const [redirectLinks, setRedirectLinks] = useState<Links[]>([ { ...

Error: Incorrect data type found in React Route component

I've encountered an issue while attempting to utilize the Route component in my application. The error message I'm receiving reads as follows: [ts] Type '{ path: "/:shortname"; component: typeof FirstComponent; }' is not assignable ...

In MUI React, the opacity of the placeholder is customizable and can be easily adjusted. This allows for the placeholder to be hidden

Currently, I am facing an issue with a filled variant TextField from Mui React. I have tried to modify it using theme components, but the placeholder text becomes hidden when the field is not focused. See here for Before Focus And here for On Focus I hav ...

transferring data from service to component

Dealing with the challenge of passing a variable from a service (LibraryService) to a component located one level deeper in the directory structure (ReadingPaneComponent) has been quite troublesome for me. This predicament arose after successfully transfer ...

Error: The object 'details.geometry.location' is not defined and cannot be evaluated

In my app, I am utilizing the react-native-google-places-autocomplete package for two fields: Current Location and Destination. The Current Location field functions flawlessly without any errors once the location is entered and the lat/lng values are set u ...

Hold on for the processing of a CSV document

I am attempting to utilize the "csv-parse" library in Typescript to read a csv file by creating an observable. The code provided uses fs.createReadStream to read the file. I am looking to return the observable and subscribe to it, but it seems that the p ...

Giving angularjs components access to controllers

I am currently working on implementing a specific behavior using AngularJS components. <parent-component> <reusable-child-component></reusable-child-component> </parent-component> My goal is to pass the parent's controller ...

Encountering a Problem with TypeScript Decorators

I've been diving into TypeScript by working on TS-based Lit Elements and refactoring a small project of mine. However, I'm starting to feel frustrated because I can't seem to figure out what's wrong with this code. Even though it' ...

Merge a series of Observables into a single Observable

I am facing a challenge where I need to merge the outcomes of various http calls into a single Observable. These calls must be executed sequentially, with each call waiting for the previous one to finish. The catch is that the number of http calls needed i ...