Reputation: 2515
I've been looking into the ES6 docs about import and export. It's pretty straightforward yet I can't get it to work. I'm just trying to import simple variables from a js file to be used inside a function. I'm using the variables accross several pages. I don't want to have to hardcode everytime. How do I achieve that?
config.js
var app_mode = 0;
if(app_mode ===0){
var mapboxtoken = 'pk.eytest';
}else{
var mapboxtoken = 'pk.eylive';
}
map.js
function mapOverview(){
mapboxgl.accessToken = mapboxtoken;//use mapboxtoken variable here
//rest of code...
}
Upvotes: 0
Views: 1616
Reputation: 4381
If you use nodejs you may export from module.exports
:
config.js
const app_mode = 0;
const mapboxtoken = (app_mode ===0) ? 'pk.eytest' : 'pk.eylive';
module.exports.mapboxtoken = mapboxtoken;
map.js
const {mapboxtoken} = require('./config.js');
// or
const config = require('./config.js');
function mapOverview(){
console.log(mapboxtoken);//use mapboxtoken variable here
//or
console.log(config.mapboxtoken);//use mapboxtoken variable here
}
mapOverview();
output:
pk.eytest
pk.eytest
also read here: import-export
Upvotes: 1
Reputation: 507
There are two main module solutions for JavaScript today.
If you use ES6, then use export
and import
:
// A.js
export const SomeConst = 'blabla'
// B.js
import { SomeConst } from 'A.js'
console.log(SomeConst) // blabla
If you use Node.js, then it's commonjs, use module.exports
and require
:
// A.js
const SomeConst = 'blabla'
module.exports.SomeConst = SomeConst
// B.JS
const SomeConst = require('A.js).SomeConst
Upvotes: 0
Reputation: 106
In the config file you need to add this piece of code maybe at the end:
export mapboxtoken;
In the map file import the variable as below(assuming both files are in the same directory):
import { mapboxtoken } from './config';
Upvotes: 0