错误:导入非法重新分配

时间:2016-12-09 09:54:36

标签: typescript rollup

我正在尝试将模块导入typescript文件,然后与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'
  }
};

1 个答案:

答案 0 :(得分:5)

非常讨厌并且不确定为什么必须以这种方式完成,但我设法通过使用assign函数设置mapbox-gl来避免错误并仍然使accessToken模块工作在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:
 * 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;
}