Error: Illegal reassignment to import

Error: Illegal reassignment to import

我正在尝试将模块导入打字稿文件,然后与 Rollup.js 捆绑在一起。

但是我收到一条错误消息,阻止 Rollup 完成。

进口:

import * as mapboxgl from 'mapbox-gl';

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

当我 运行 tsc 时没有任何错误信息,但是当我 运行:

$ rollup -c rollup.config.js

Illegal reassignment to import 'mapboxgl'
Error: Illegal reassignment to import 'mapboxgl'
at error (C:\Users\m.wilson\AppData\Roaming\npm\node_modules\rollup\src\utils\error.js:2:14)
at disallowIllegalReassignment (C:\Users\m.wilson\AppData\Roaming\npm\node_modules\rollup\src\ast\nodes\shared\disallowIllegalReassignment.js:9:4)
at Node.bind (C:\Users\m.wilson\AppData\Roaming\npm\node_modules\rollup\src\ast\nodes\AssignmentExpression.js:12:3)
at C:\Users\m.wilson\AppData\Roaming\npm\node_modules\rollup\src\ast\Node.js:6:34
at Node.eachChild (C:\Users\m.wilson\AppData\Roaming\npm\node_modules\rollup\src\ast\Node.js:21:5)
at Node.bind (C:\Users\m.wilson\AppData\Roaming\npm\node_modules\rollup\src\ast\Node.js:6:8)
at Node.bind (C:\Users\m.wilson\AppData\Roaming\npm\node_modules\rollup\src\ast\nodes\BlockStatement.js:8:9)
at Node.bind (C:\Users\m.wilson\AppData\Roaming\npm\node_modules\rollup\src\ast\nodes\FunctionExpression.js:7:13)
at C:\Users\m.wilson\AppData\Roaming\npm\node_modules\rollup\src\ast\Node.js:6:34
at Node.eachChild (C:\Users\m.wilson\AppData\Roaming\npm\node_modules\rollup\src\ast\Node.js:21:5)
Type rollup --help for help, or visit https://github.com/rollup/rollup/wiki

我已经缩小范围,错误仅在存在 (mapboxgl as any).accessToken = this.accessToken; 时发生。

我的 rollup.config.js 看起来像这样:

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

非常烦人,不确定为什么必须这样做,但我设法避免了错误,并且仍然通过使用分配函数设置 [=13] 使 mapbox-gl 模块工作=] 在 mapboxgl

所以我改变了:

import * as mapboxgl from 'mapbox-gl';

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

为此:

import * as mapboxgl from 'mapbox-gl';

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

/*
 *
 * credit to this answer for the assign function:
 * 
 *
 */
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;
}