'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.
  1. 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 module

  2. After having added "type": "module" to my package.json, running truffle migrate --reset gives 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.
  1. I then tried running truffle migrate --reset --config truffle-config.cjs but it threw the same error as in 1.
  2. I finally tried to modify the type in my package.json to commonjs and ran truffle migrate --reset but 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