[英]How to consume NPM packages in the browser with TypeScript?
這是我的設置:
的index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="../node_modules/systemjs/dist/system.js"></script>
<script src="../node_modules/lodash/index.js"></script>
</head>
<body>
<script>
System.config({
packages: {'js': {defaultExtension: 'js'}}
});
System
.import('./js/app')
.catch(console.error.bind(console));
</script>
</body>
</html>
app.ts
import {_} from 'lodash';
export class App {};
當我嘗試將TypeScript轉換為JavaScript時,出現以下錯誤:
error TS2307: Cannot find module 'lodash'.
使用TypeScript時,將NPM壓縮文件加載到項目中的最標准/推薦方式是什么?
筆記
node_modules
,並且正確提供了文件node_modules/lodash/index.js
。 Bower
因為我發現應該使用NPM
代替。 SystemJS
,我相信它是通用模塊加載器。 首先,打字稿找不到您的模塊,因為您需要將鍵入內容放入文件中。 其次,您需要使用--module系統標志(或tsconfig.json中的等效標志)導出打字稿。 第三,它需要使用systemjs加載。 我強烈建議您為此使用JSPM,我知道我知道-另一個程序包管理器,但它比NPM更為重要。 它使您可以非常輕松地管理Systemjs部門。 http://jspm.io/
恐怕我不熟悉SystemJ,但是據我所知的模塊加載器,它們通過它們從中加載的路徑識別庫,而不是模塊的全局名稱或其他任何東西。 因此,通過<script>
加載lodash實際上不會幫助它知道它是否具有它,或要返回什么對象。 從根本上講,您將希望通過模塊加載器加載它,而不是自己加載。
但是,您可能不想在腳本中的所有require語句中寫入“ ../node_modules/ ”。 那會很煩。 您可以瀏覽SystemJs的配置文檔,以查看是否有創建映射的方法,以便特定的模塊名稱將自動使其知道使用腳本的特定路徑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.