Here is my first file:
var self = this;
var config = {
'confvar': 'configval'
};
I want this configuration variable in another file, so I have done this in another file:
conf = require('./conf');
url = conf.config.confvar;
But it gives me an error.
TypeError: Cannot read property ‘confvar’ of undefined
What can I do?
Edit (2020):
Since Node.js version 8.9.0, you can also use ECMAScript Modules with varying levels of support. The documentation.
--experimental-modulesOnce you have it setup, you can use
importandexport.Using the example above, there are two approaches you can take
./sourceFile.js:
./consumer.js:
./sourceFileWithoutDefault.js:
./consumer2.js
You can re-export anything from another file. This is useful when you have a single point of exit (index.
{ts|js}) but multiple files within the directory.Say you have this folder structure:
You could have various exports from both store.js and my-component.js but only want to export some of them.
./src/component/myComponent.js:
./src/component/state.js:
./src/component/index.js
./src/index.js
Original Answer:
You need module.exports:
For example, if you would like to expose
variableNamewith value"variableValue"onsourceFile.jsthen you can either set the entire exports as such:Or you can set the individual value with:
To consume that value in another file, you need to
require(...)it first (with relative pathing):Alternatively, you can deconstruct it.
If all you want out of the file is
variableNamethen./sourceFile.js:
./consumer.js: