How Import Object From External Js File In React Js Using Web Pack
Solution 1:
You need to export Jobs from jobs.js in order to import it into another module. And jobs.js doesn't need to be a function if your just exporting static data. So, you can make jobs.js look like this:
export default {
jobs: [
{
jobType: "Web developer",
desc: "Creates website"
},
{
jobType: "Bin Man",
desc: "Collects bins"
}
]
};
Then you can import it like so:
importJobsfrom'./data/jobs.js';
Or:
var Jobs = require('./data/jobs.js').default;
If you want to require with normal commonjs syntax then you can make jobs.js like this:
module.exports = {
jobs: [
{
jobType: "Web developer",
desc: "Creates website"
},
{
jobType: "Bin Man",
desc: "Collects bins"
}
]
};
Which allows you to require like so:
varJobs = require('./data/jobs.js');
Solution 2:
Let's say the file you're keeping your data in is called "file.js."
var text = "Hello world!"; //In file.js
Below this line, You must export this variable so that it can be imported in the React code:
module.exports = {data: text} //In file.js
The string is stored as an object called "data." You then import the contents of "file.js" in the file you wish to use it, let's say App.jsx".
import file from'./file.js'; //In App.jsx
The contents of the object you exported in the other file is being stored as the variable "file" here. You can then convert the contents of "file" to an object:
var str = file.data; //"data"is the object within "file"
Your string, "Hello world!", is now stored within the variable str.
Hope this helps!
Post a Comment for "How Import Object From External Js File In React Js Using Web Pack"