我正在為打字稿做一些測驗設定。我的主要重點是將所有.ts模塊捆綁到一個.js檔案中,該檔案可以在簡單的index.html. 這是我的測驗模塊:
// index.ts
import { Example } from './example'
class x {
example(): void {
console.log(Example)
}
}
let test = new x()
test.example()
// example.ts
export const Example : string = 'Example Message'
bundle.js我使用 Webpack 5 和 ts-loader 將所有內容編譯成一個檔案。然后,我創建了一個.html檔案來測驗創建的類。內部(然后)正確執行,但第二個,在報告test.example()內部。index.tsbundle.js<script/>Uncaught ReferenceError: x is not defined
<!-- index.html -->
<html>
<script src="../dist/js/bundle.js"></script>
<script>
// Uncaught ReferenceError: x is not defined
let test = new x()
test.example()
</script>
</html>
如何從第二個參考我的類 x <script/>?
uj5u.com熱心網友回復:
如何從第二個參考我的類 x
<script/>?
你不能。至少在不修改源代碼結構的情況下是這樣。
捆綁器將所有可執行代碼放入捆綁包中。這包括您的依賴項和您的應用程式代碼。所有這些都只是真正設計為通過importandexport關鍵字在該捆綁包中作業。
捆綁器以不污染全域范圍的方式管理這些匯入/匯出。但這確實要求您留在該捆綁包中。
但是,您似乎希望您的包在該全域范圍內提供一些值。為此,您必須明確說明。
class x {
example(): void {
console.log(Example)
}
}
// Add `x` to the browser's global scope.
window.x = x
現在從其他一些<script>標簽new x()應該可以按您的預期作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/422401.html
標籤:
