用rollupjs、es2015模块导入

import with rollupjs, es2015 modules

本文关键字:模块 导入 es2015 rollupjs      更新时间:2023-09-26

我使用rollupjs作为新的ionic2@RC.0版本的一部分。这个项目是用tsconfig.jsoncompilerOptions.module = "es2015"代替"commonjs",这对我来说是全新的。

// typescript
import { AgmCoreModule } from 'angular2-google-maps/core';

我得到这个import错误从rollup

[17:40:45]  typescript compiler finished in 8.08 s
[17:40:45]  bundle dev started ...
[17:40:55]  Error: Module .../node_modules/angular2-google-maps/core/index.js does not export AgmCoreModule (imported by .../.tmp/shared/shared.module.js)
    at Module.trace (.../node_modules/rollup/dist/rollup.js:7677:29)
    at ModuleScope.findDeclaration 
    ...

导入文件如下所示

// index.d.ts
/**
 * angular2-google-maps - Angular 2 components for Google Maps
 * @version v0.14.0
 * @link https://github.com/SebastianM/angular2-google-maps#readme
 * @license MIT
 */
export * from './directives';
export * from './services';
export * from './map-types';
export { LatLngBounds, LatLng, LatLngLiteral, MapTypeStyle } from './services/google-maps-types';
export * from './core-module';

// index.js
/**
 * angular2-google-maps - Angular 2 components for Google Maps
 * @version v0.14.0
 * @link https://github.com/SebastianM/angular2-google-maps#readme
 * @license MIT
 */
"use strict";
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
// main modules
__export(require('./directives'));
__export(require('./services'));
// Google Maps types
// core module
__export(require('./core-module'));
//# sourceMappingURL=index.js.map

我可以将导入更改为

import { AgmCoreModule } from 'angular2-google-maps/core/core-modules';

rollup没有抱怨,但是angular2找不到从angular2-google-maps/core

导入的指令。

我该怎么办?

angular2-google-maps/core/index.ts中的export * from ...声明使用__export函数编译为JS时,Rollup失去了跟踪导出绑定的能力。如果你使用esm/ (ECMAScript模块)目录下的ES6版本的库,一切都应该正常。

import { AgmCoreModule } from 'angular2-google-maps/esm/core/index.js';

对于发布候选版本,Ionic 2从基于gulp的构建过程转变为现在使用rollup.js进行捆绑的构建过程。大多数时候,第三方库"只是工作"——然而在某些情况下(取决于库如何导出其组件),您需要显式地告诉rollup.js正在导出什么。这就是Angular 2的谷歌地图。

这在Ionic 2 App Build Scripts文档页面的"Building"部分中有记录。简而言之,您需要为您的项目创建一个自定义Rollup .config.js文件,以告诉Rollup有关AgmCoreModule 的信息。

这是一篇完整记录了具体步骤的博客文章。此外,这里有一个Github repo,其中显示了完整的功能代码。