Web3js
TypeError:web3_1.default 不是建構子
我正在嘗試將使用 web3.js 的 DApp 從 JavaScript 轉換為 TypeScript,但我遇到了一堆執行時錯誤。我正在使用 Visual Studio Code IDE,並且正在編譯為 ES6。我已將項目縮減為仍然存在這些問題的最小程式碼。
有人可以幫我解決這個問題嗎?提前致謝!
(如果我忘記包含一些重要資訊,請隨時發表評論)
NPM 包:
- @types/web3(版本 1.0.12)
- web3(版本 1.0.0-beta.36)
網頁:
<script src="system.js"></script> <script> System.config({ baseURL: './out', packages: { './out': { defaultJSExtensions: 'js' } }, meta: { '*': { format: 'register' } }, }); window.addEventListener("load", (async function(){ await System.import("init"); })); </script>
初始化.ts:
import Web3 from "web3"; const ABI: any[] = []; let web3: Web3; export async function init() { if (typeof (window as any).web3 !== "undefined") { const injectedWeb3: Web3 = ((window as any).web3 as Web3); web3 = new Web3(injectedWeb3.currentProvider); // This line produces the error: TypeError: web3_1.default is not a constructor } else { web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); } const myABIinstance = new web3.eth.Contract(ABI); } init();
執行時錯誤的完整堆棧跟踪:
TypeError: web3_1.default is not a constructor init.ts:10 at /home/jesse/MinimalWeb3Typescript/init.ts:10:16 at Generator.next (<anonymous>) at /home/jesse/MinimalWeb3Typescript/out/init.js:8:76 at new Promise (<anonymous>) at __awaiter (/home/jesse/MinimalWeb3Typescript/out/init.js:4:17) at init (/home/jesse/MinimalWeb3Typescript/out/init.js:14:17) at Object.execute (/home/jesse/MinimalWeb3Typescript/init.ts:18:1) at U (/home/jesse/MinimalWeb3Typescript/system.js:4:8818) at /home/jesse/MinimalWeb3Typescript/system.js:4:11430 at /home/jesse/MinimalWeb3Typescript/system.js:4:11499
如果使用最近的 web3(例如
1.0.0-beta.50
),可能的補救措施是設置esModuleInterop
:{ "compilerOptions": { "esModuleInterop": true } }
嘗試如下更改您的程式碼:
const Web3 = require('web3'); declare var window: any; const ABI: any[] = []; let web3: any; export async function init() { if (typeof window.web3 !== 'undefined') { // Use Mist/MetaMask's provider this.web3 = new Web3(window.web3.currentProvider); } else { console.warn('No web3 detected.'); } } init();
並首先檢查它是否有效。如果是這樣,您可以進行其他更改。