Web3js

模組解析失敗:不能在非同步函式之外使用關鍵字“等待”

  • September 30, 2021

我收到一條錯誤消息。我將 tsconfig.json 設置為使用“es2017”等待。它仍然沒有編譯。不知道如何將 Web3Modal 配置為 Button。

GitHub連結:https ://github.com/GoGetterMeme/usedapp

./src/App.tsx 30:17 模組解析失敗:不能在非同步函式之外使用關鍵字“await”(30:17)使用這些載入器處理文件:

  • ./node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js
  • ./node_modules/react-scripts/node_modules/babel-loader/lib/index.js 你可能需要一個額外的載入器來處理這些載入器的結果。| | });

常量提供者 = 等待 web3Modal.connect(); | const web3 = new Web3(provider); |>

import React from 'react';
import { ChainId, DAppProvider } from "@usedapp/core";
import { Box, Button, Container } from "@material-ui/core";
import Web3 from "web3";
import Web3Modal from "web3modal";
import WalletConnectProvider from "@walletconnect/web3-provider";

const providerOptions = {
 walletconnect: {
   package: WalletConnectProvider, // required
   options: {
     infuraId: process.env.REACT_APP_INFURA_ID // required
   }
 }
};

const web3Modal = new Web3Modal({
 network: "rinkeby", // optional
 cacheProvider: true, // optional
 providerOptions // required
});

const provider = await web3Modal.connect();

const web3 = new Web3(provider);



function App() {
 return (
   <DAppProvider config={{
     supportedChains: [ChainId.Rinkeby],
     notifications: {
       expirationPeriod: 1000,
       checkInterval: 1000
     }
   }}>
     <Container maxWidth="md">
       <Box>
         <Button variant="contained" color="primary">Connect</Button>
       </Box>
     </Container>
   </DAppProvider>
 )
}

export default App

這裡的實際問題是你await在 JS 的頂層使用,你可以通過做這樣的事情來避免這個問題(但值得注意的是,在這之後你可能會遇到其他問題 - 因為沒有什麼真的正在使用該web3變數完成):

import React from 'react';
import { ChainId, DAppProvider } from "@usedapp/core";
import { Box, Button, Container } from "@material-ui/core";
import Web3 from "web3";
import Web3Modal from "web3modal";
import WalletConnectProvider from "@walletconnect/web3-provider";

const providerOptions = {
 walletconnect: {
   package: WalletConnectProvider, // required
   options: {
     infuraId: process.env.REACT_APP_INFURA_ID // required
   }
 }
};

const web3Modal = new Web3Modal({
 network: "rinkeby", // optional
 cacheProvider: true, // optional
 providerOptions // required
});

function App() {

 const connectWallet = async () => {
   const provider = await web3Modal.connect();
   const web3 = new Web3(provider);
 }

 return (
   <DAppProvider config={{
     supportedChains: [ChainId.Rinkeby],
     notifications: {
       expirationPeriod: 1000,
       checkInterval: 1000
     }
   }}>
     <Container maxWidth="md">
       <Box>
         <Button onClick={() => connectWallet()} variant="contained" color="primary">Connect</Button>
       </Box>
     </Container>
   </DAppProvider>
 )
}

export default App

引用自:https://ethereum.stackexchange.com/questions/110787