2017-09-15 60 views
1

我遇到了一個問題,我似乎無法在打字稿文件中導入bootstrap js。我需要這個來打開一個模式。無法在TS腳本中導入引導程序庫

我的打字稿腳本:

import $ from 'jquery'; 
import 'bootstrap'; 

$('#btn').click(function() { 
    $('#test').text('sasasa'); 
}); 

我的觀點

<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button> 

<div id="myModal" class="modal fade" role="dialog"> 
    <div class="modal-dialog"> 
     <div class="modal-content"> 
      <div class="modal-header"> 
       <button type="button" class="close" data-dismiss="modal">&times;</button> 
       <h4 class="modal-title">Modal Header</h4> 
      </div> 
      <div class="modal-body"> 
       <p>Some text in the modal.</p> 
      </div> 
      <div class="modal-footer"> 
       <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> 
      </div> 
     </div> 
    </div> 
</div> 

<div class="row"> 
    <div class="panel panel-default"> 
     <div class="panel-heading"> 
      <h3 class="panel-title"> 
       test 
      </h3> 
     </div> 
     <div class="panel-body"> 
      <span id="test">Test</span> 

      <button id="btn">Klik</button> 
     </div> 
    </div> 
</div> 

@section scripts { 
    <environment names="Development"> 
     <script src="~/js/quotation-test.js"></script> 
    </environment> 
    <environment names="Staging,Production"> 
     <script src="~/js/quotation-test.js" asp-append-version="true"></script> 
    </environment> 
} 

當我運行上面的打字稿腳本我得到了我的控制檯以下錯誤:

Uncaught ReferenceError: jQuery is not defined 
    at Object.562 (quotation-test.js:103) 
    at __webpack_require__ (common.js:55) 
    at Object.561 (quotation-test.js:27) 
    at __webpack_require__ (common.js:55) 
    at Object.560 (quotation-test.js:13) 
    at __webpack_require__ (common.js:55) 
    at webpackJsonpCallback (common.js:26) 
    at quotation-test.js:1 

然而,當我刪除import 'bootstrap'行,btn點擊處理程序工作得很好。所以看起來像jQuery被正確導入。

手動添加腳本(即:)

<!-- Latest compiled and minified CSS --> 
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> 

<!-- jQuery library --> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 

<!-- Latest compiled JavaScript --> 
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> 

模態工作正常,但我寧願不走這條路。有沒有人有什麼建議?我在網上找不到任何似乎有同樣問題的資源。

我(的相關部分)package.json

"@types/bootstrap": "^3.3.36", 
    "bootstrap": "^3.3.7", 
    "jquery": "^3.2.1", 

有沒有人有什麼建議?任何幫助將不勝感激。

回答

0

mb bootstrap使用「JQuery」,而不是「$」。嘗試「導入'jquery';」或「導入{jQuery}'jquery';」

1

當使用ES6/CommonJS導入導入jQuery時,它不會創建包含bootstrap包所依賴的全局變量。你需要明確創建全局jQuery變量,以便引導可以使用它:

import $ from 'jquery'; 
window['jQuery'] = $; 
import 'bootstrap'; 
+0

這並不太爲我工作(有大約'Window'沒有一個指標籤名打字稿錯誤),但你的答案駕馭了我在正確的方向,我發現這個解決方案:https://stackoverflow.com/a/39283602/3061857,這工作。謝謝! – nbokmans