'Import variables and functions from a js file into migration file and test file with truffle
I have a file in my project folder called `helpfulSuff.js` where I have global variables and functions which I would like to use in both my migration files and my test files.
However, when I try to import the variables into the migration files, the following error is thrown when trying to migrate the contract:
SyntaxError: Cannot use import statement outside a moduleAfter having added
"type": "module"to mypackage.json, runningtruffle migrate --resetgives the following error:
Error [ERR_REQUIRE_ESM]: require() of ES Module /home/nic/Documents/blockchain/kittyFinance/truffle-config.js from /usr/local/lib/node_modules/truffle/node_modules/original-require/index.js not supported.
truffle-config.js is treated as an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which declares all .js files in that package scope as ES modules.
- I then tried running
truffle migrate --reset --config truffle-config.cjsbut it threw the same error as in 1. - I finally tried to modify the type in my
package.jsontocommonjsand rantruffle migrate --resetbut it gave me the error mentioned in 1. again
Thank you for your help!
My current files:
./helpfulSuff.js
const tokenConstants {
NAME: "Kitty Finance",
SYMBOL: "KTFN",
INITIAL_SUPPLY: 10000000
};
export { tokenConstants };
./migrations/2_deploy_contracts.js
const Token = artifacts.require("Token");
import { tokenConstants } from '../helpful_stuff';
/*const name = "Kitty Finance";
const symbol = "KTFN";
const initialTokenSupply = 10000000; // 10 million tokens initial supply*/
var token;
module.exports = function (deployer, network, accounts) {
if (network == "development") {
return deployer.deploy(
Token,
tokenConstants.NAME,
tokenConstants.SYMBOL,
tokenConstants.INITIAL_SUPPLY,
{ from: accounts[0] })
.then(function(instance) {
token = instance;
})
}
};
./package.json
{
"dependencies": {
"@openzeppelin/contracts": "^4.5.0",
"@truffle/hdwallet-provider": "^2.0.4",
"dotenv": "^16.0.0"
},
"type": "commonjs"
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
