2

I am trying to define constants in one file and use them in another.

I know this wont work but what is the correct way to do this?

// const.js
export const GREETING = `Hello, ${name}`;

// displayGreeting.js
import { GREETING } from './const';
def displayGreeting(name) {
  return GREETING
}

>>> displayGreeting('barry')
>>> Hello, barry
moto
  • 946
  • 10
  • 27
  • You could create `const GREETING = name => \`Hello, ${name}\`;` and then use `GREETING(name)` inside `displayGreeting` – adiga Jun 11 '19 at 12:27

2 Answers2

2

Instead of exporting a string (defined with a template literal), export a function which takes a parameter, which is then interpolated into a returned template literal:

export const makeGreeting = name => `Hello, ${name}`;

and

import { makeGreeting } from './const';
makeGreeting('barry');

Also, def displayGreeting(name) { is not valid Javascript - declare functions with function, or () =>, or something of the sort.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
-1
// const.js - exports a function
export const greeting = name => `Hello, ${name}`;

// index.js
import { greeting } from "./const";
const greetBarry = GREETING("barry");
console.log(greetBarry);

//Hello, barry

Codesandbox

ksav
  • 20,015
  • 6
  • 46
  • 66