I am new to truffle and webpack. Currently, I am writing all my code into this one app.js file. Suppose I would like to have an external js file which is used to do some initializations.

Currently, my app.js is something like:

// Import libraries we need.
import { default as Web3} from 'web3';
import { default as contract } from 'truffle-contract'

// Import our contract artifacts and turn them into usable abstractions.
import user_artifacts from '../../build/contracts/User.json';
var User = contract(user_artifacts);
var accounts;
var g, c;

window.App = {
  start: function() {
    var self = this;

    web3.eth.getAccounts(function(err, accs){
      if (err) {
        alert("Error loading accounts");
      if (accs.length == 0) {
        alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly.");
      accounts = accs;

    // Load/Initiatize these variables from an external js files
    g = document.getElementById("government-register");
    c = document.getElementById("customer-register");
window.addEventListener('load', function() {
    window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));


I want to load the variables g & c from an external js file and use them anywhere in app.js. Similarly how to use functions from an external js file in app.js.

1 Answer 1


A function cannot be called unless it was defined in the same file or one loaded before the attempt to call it.

A function cannot be called unless it is in the same or greater scope then the one trying to call it.

You declare function fn1 in first.js, and then in second you can just have fn1();

1.js :

function fn1 (){

2.js :


index.html :

<script type="text/javascript" src="1.js"></script>
<script type="text/javascript" src="2.js"></script>

It works fine :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.