Not able to access variables in required file

123 Views Asked by At

I'm using browserify on a project and am running in to the following:

I have a file test.js. In test.js there is nothing but the following:

var test = 'test';

Now, in the same directory I have my main file 'app.js'. I require test.js and try to access the 'test' like so:

var testing = require(./test.js);
alert(test);

This fails and the console returns 'test is undefined'.

Now, I did try putting this in 'test.js' instead:

module.exports = {
    test: 'test'
}

and the in app.js:

var testing = require(./test.js);
alert(testing.test);

and this does work but it isn't what I want. I don't want to have to define every single variable, function, etc. in an object. I want the entire file of test.js code to to be written in by gulp before the code in app.js as if it were a server include or as if both files were in the 'head' element and test.js was written in first.

Is this sort of behavior even possible?

1

There are 1 best solutions below

0
On BEST ANSWER

Without custom logic, it's not possible to achieve what you want. However I believe you could find a compromise by using ES6 modules instead of CommonJS modules.

You would be able to write

export var test = 'test';

which declares and exports a variable test. You can then import it with

import {test} from './test';

Since you are using browserify, plugging in an ES6 module to CommonJS converter is pretty straightforward. E.g. you could use Babel.