0

I am having the following *.js file:

var text = `
This is a test ${Company.Name}.
`

module.exports = {
    text
};

My main file looks like the following:

const Company = {}
Company.Name = "Apple"

Basically, I would like to "render" the text and fill it with my predefined variable.

Any suggestions what is the best way to "load" the text file in the main file?

I appreciate your replies!

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Carol.Kar
  • 4,581
  • 36
  • 131
  • 264
  • Better to export `Company.Name` from `*.js` file. – Saurabh Agrawal May 27 '19 at 04:49
  • 1
    Given that `Company.Name` is "nothing" in your js file, why not export a function? (e.g. ```module.exports = Company => `This is a test ${Company.name}```) Because right now the code you're showing doesn't really make any sense, modules are supposed to be self contained: anything they need, you either require in the module, it it's specified at call time. There is no "relying on magical global values". – Mike 'Pomax' Kamermans May 27 '19 at 04:51
  • Maybe relevant: https://stackoverflow.com/questions/30003353/can-es6-template-literals-be-substituted-at-runtime-or-reused – Robby Cornelissen May 27 '19 at 04:55
  • @Mike'Pomax'Kamermans How would you structure the code differently? – Carol.Kar May 27 '19 at 05:25
  • @Anna.Klee: The comment mentions a function – if you export the function ``text: Company => `This is a test ${Company.name}`,`` instead of a direct literal ``text: `This is a test ${Company.name}`,``, you can call the function from the other file and get the string you want back. That’s probably the least awkward way to accomplish it, if possible. (Also rahamanabdurar’s answer.) – Ry- May 27 '19 at 07:31
  • I'd either export a function (I showed a "fat arrow" function but you can also use a normal one: ```module.exports = function(company) { return `text blah ${company.someval}`;}``` but really, what you're showing is code that belongs in your `Company` class, so you can call `Company.getNamedString()` or whatever feels the most appropriate name? – Mike 'Pomax' Kamermans May 27 '19 at 16:02

2 Answers2

1

in *.js file

var text = (Company)=> `This is a test ${Company.Name}.`

module.exports = {
    text
};

in main.js file

let { text }  = require('./hello');

const Company = {}
Company.Name = "Apple"

let try = text(Company);
console.log(try):
Abdur Rahaman
  • 197
  • 2
  • 12
0

Just import it:

const { text } = require("./*");
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79