I'm thinking there's gotta be a way to load the abi
(or the entire JSON
build
file) of a smart contract
into my front-end Javascript
app after compilation automatically - meaning via some kind of config
script.
That way I don't have to copy-paste the abi
into the Javascript
code manually, after every single edit and compilation I make on my smart-contract.
But how?
NOTE: I'm not using Node.js
here, we're talking pure front-end vanilla javascript
file.
Webpack
's website clearly states that: beginning with Webpack version 2.0.0 json loaders
are no longer needed.
Well right now I'm trying this and getting an error:
import * as contractArtifact from "../build/contracts/MySmartContract.json"
The error is:
import declarations may only appear at top level of a module
For what it's worth, my code for instantiating the contract in my Javascript code - which works perfectly - is as follows:
contractArtifact = {
"contractName": "MyContract",
"abi": [
{
"inputs": [
{
"internalType": "string",
"name": "name",
"type": "string"
},
...
...etc...
}
contractABI = contractArtifact["abi"];
// Get the Contract's ADDRESS:
network = Object.keys(contractArtifact.networks)[0];
contractAddress = contractArtifact.networks[network].address;
// Now instantiate the Contract using the ABI and the Address:
contractInstance = new web3Instance.eth.Contract(contractABI, contractAddress);
So this works perfectly - I just don't want to have to manually copy-paste that entire JSON
file into here every single time I make the tiniest change to and then compile my smart-contract.
import
andrequire
statements are designated to be used for JS files only. They can be used in order to load code from another file into your JS script. What you are trying to do is to load data from another file into your JS script. If your JSON file started withmodule.exports =
, then your import attempt would probably work. But that would effectively turn it from a JSON file into a JS file (regardless of the extension used).const fs = require("fs");
, you could simply do:const contractArtifact = JSON.parse(fs.readFileSync("../build/contracts/MySmartContract.json", {encoding: "utf8"}));