2016-10-08 31 views
0

我的Angular 2編碼爲typescript 2的應用程序使用the Intl.js polyfill如何使用Intl.js作爲rollup.js中的es2015模塊構建

我已將module:"es2015"設置爲tsconfig.json以允許使用Rollup.js作爲recommended by Angular進行樹形抖動。在我的組件我只是做import 'intl'

當我運行在瀏覽器中的應用程序,我得到的錯誤

global is not defined

我一直在使用rollup-plugin-commonjs圖書館轉換爲es2015

rollup.config嘗試.js

plugins: [ 
     nodeResolve({jsnext: true, module: true}), 
     commonjs({ 
      include: 'node_modules/intl/**/*', 
     }) 
] 

當我在瀏覽器中運行應用程序時,我ge t的誤差:

IntlPolyfill is not defined

在線:

IntlPolyfill.__addLocaleData({locale:"en-US",...});

I noticed here該庫是用es6所以它應該是與rollup兼容。有關如何使用此庫作爲es6模塊的任何提示?

回答

2

要使用Intl.js作爲ES6模塊,你要麼需要

  1. 說服維護者發佈的ES模塊版本一起在dist文件夾中的其他文件(如Intl.esm.js等) ,使用package.jsonmodulejsnext:main領域 - 他們已經使用匯總生成其UMD建那麼這將是一個簡單的加法,或
  2. 建立它自己,使用src文件,注意使用相同的巴貝爾配置等

但是你可以使用它的當前形式使用rollup-plugin-commonjs。事實證明,你只需要確保你要導入的dist/Intl.js文件,而不是index.js文件(可能是由於一些棘手的週期性相關性,這在CommonJS的他們在ES模塊是如何工作的工作方式不同,以):

import 'intl/dist/Intl.js'; 
console.log(Intl); // works! 

這將產生比導入index.js更好的結果,即使它可以工作,因爲dist文件是直接從ES模塊生成的(沒有繁瑣的CommonJS轉換)。

+0

一個問題是我只使用'en-us'語言環境,因此我編輯了'intl/index.js'並將第6行從[this]改爲(https://github.com/andyearnshaw/Intl.js /blob/master/index.js#L6)到[this](http://pastebin.com/GfYSL7t2)。這使我大大減少了包的大小。您的解決方案是否可以適應您的想法? – BeetleJuice

+0

一種方法是使用[rollup-plugin-replace](https://github.com/rollup/rollup-plugin-replace)將'locale-data/complete.js'替換爲'locale-data/jsonp/ES-US.js' –

相關問題