importing files from a folder within local directory React - javascript

I have a react project. I am trying to grab all of the files from a help folder and store them in an array or object to be iterated throught within a react component. I am not sure how to do this. i tried a few differnt things....
Here is the directory:
i tried:
import * as files from '../../../public/help/';
and
var req = require.context('../../../public/images/help', false);
console.log(typeof req)
console.log(req)
req.keys().forEach(function(key){
console.log(req(key));
});

You can get the path of public folder using process.env.PUBLIC_URL
in your case the path you want will be process.env.PUBLIC_URL + "/help"
and this might also work,
window.location.origin + "/help"

Related

Include JSON files into React build

I know this question maybe exist in stack overflow but I didn't get any good answers, and I hope in 2020 there is better solution.
In my react app I have a config JSON file, it contains information like the title, languages to the website etc..
and this file is located in 'src' directory
{
"headers":{
"title":"chat ",
"keys":"chat,asd ,
"description":" website"
},
"languages":{
"ru":"russian",
"ar":"arabic",
"en":"English"
},
"defaultLanguage":"ru",
"colors":{
"mainColor":"red",
"primary":"green",
"chatBackGround":"white"
}
}
I want to make my website easy to edit after publishing it, but after I build my app, I can't find that settings.json file there in build directory.
I find out that files in public directory actually get included to build folder, I tried to put my settings.JSON in public,
but react won't let me import anything outside of src directory
I found other solutions like this one but didn't work
https://github.com/facebook/create-react-app/issues/5378
Also I tried to create in index.html a global var like (window.JSON_DATA={}), and attach a JS object to it and import it to App.js, but still didn't work.
How can I make a settings JSON file, and have the ability to edit it after publishing the app?
Add your settings.json to the public folder. React will copy the file to the root of build. Then load it with fetch where you need it to be used. For example if you need to load setting.json to the App.js then do the next:
function App() {
const [state, setState] = useState({settings: null});
useEffect(()=>{
fetch('settings.json').then(response => {
response.json().then(settings => {
// instead of setting state you can use it any other way
setState({settings: settings});
})
})
})
}
If you use class-components then do the same in componentDidMount:
class CustomComponent extends React.Component {
constructor(props) {
super(props);
this.state = {settings: null};
}
componentDidMount() {
fetch('settings.json').then(response => {
response.json().then(settings => {
this.setState({settings: settings});
})
})
}
}
Then you can use it in render (or any other places of your component):
function App() {
...
return (
{this.state.settings && this.state.settings.value}
)
}
The easiest way would be to require() the file on the server during server side rendering of the html page and then inline the json in the html payload in a global var like you mentioned window.JSON_DATA={}. Then in your js code you can just reference that global var instead of trying to use import.
Of course this approach would require you to restart your server every time you make a change to the json file, so that it get's picked up. If that is not an option then you'll need to make an api call on the server instead of using require().
You may want to look at using npm react-scripts (https://www.npmjs.com/package/react-scripts) to produce your react application and build. This will package will create a template that you can put your existing code into and then give you a pre-configure build option that you can modify if you would like. The pre-configured build option will package your .json files as well. Check out their getting started section (https://create-react-app.dev/docs/getting-started/)
If you don't want to go that route, and are just looking for quick fix, then I would suggest change your json files to a JS file, export the JS object and import it in the files you need it since you seem to be able to do that.
//src/sampledata.js
module.exports = {
sample: 'data'
}
//src/example.jsx (this can also be .js)
const sampledata = require('./sampledata');
console.log(sampledata.sample); // 'data'
you can use 'Fetch Data from a JSON File'
according to link
https://www.pluralsight.com/guides/fetch-data-from-a-json-file-in-a-react-app
example

Importing local HTML page with fetch into another HTML page

Basically, I have a html file called panel containing a simple DIV that I would like to insert into another main HTML file.
Instead of using web components, I'd like to implement a simple solution as described in this answer.
So, here is what I am doing for testing (just logging the panel to console):
panel.html
<div id="panel">
<h1>It works...</h1>
</div>
get-template.ts
export async function getTemplate(filepath: string, selectors: string) {
let response = await fetch(filepath);
let txt = await response.text();
let html = new DOMParser().parseFromString(txt, 'text/html');
return html.querySelector(selectors);
}
main.ts
import { getTemplate } from './get-template'
getTemplate('/path/to/panel.html','#panel').then((panel) => {console.log(panel);})
The console logs "null".
If this info could make any difference, I am using parcel-bundler to build the application.
The actual problem was determined by #CBroe and was about the fact that when parcel builds my application, the file path of my panel.html resource changes to be relative to the built dist folder.
Just to clarify:
before building the path is relative to the main.ts file
after building the path is relative to the dist folder
So the solution is to think about the final URL the panel.html will have, and refer to it in advance before building with parcel.
Something like this would work in my case:
main.ts (new)
import { getTemplate } from './get-template'
getTemplate('./panel.html','#panel').then((panel) => {console.log(panel);})
Then of course, the other step will be to copy the actual panel.hml file into the dist directory, otherwise the URL will point to a non existing file.
I see there was a github issue about automatically copy static (or assets) files in the parcel repository, and one of the solution provided is to use the plugin parcel-plugin-static-files-copy.

How to import a module from the static using dynamic import of es6?

I'm trying to add dynamic import into my code to have a better performance on the client-side. So I have a webpack config where is bundling js files. On SFCC the bundled files are in the static folder where the path to that files is something like this: /en/v1569517927607/js/app.js)
I have a function where I'm using dynamic import of es6 to call a module when the user clicks on a button. The problem is that when we call for that module, the browser doesn't find it because the path is wrong.
/en/lazyLoad.js net::ERR_ABORTED 404 (Not Found)
This is normal because the file is on /en/v1569517927607/js/lazyLoad.js.
There is a way to get it from the right path? Here is my code.
window.onload = () => {
const lazyAlertBtn = document.querySelector("#lazyLoad");
lazyAlertBtn.addEventListener("click", () => {
import(/* webpackChunkName: "lazyLoad" */ '../modules/lazyLoad').then(module => {
module.lazyLoad();
});
});
};
I had the same problem and solved it using the Merchant Tools > SEO > Dynamic Mapping module in Business Manager.
There you can use a rule like the following to redirect the request to the static folder:
**/*.bundle.js i s,,,,,/js/{0}.bundle.js
All my chunk files are named with the <module>.bundle pattern.
Here you can find more info :
https://documentation.b2c.commercecloud.salesforce.com/DOC1/topic/com.demandware.dochelp/content/b2c_commerce/topics/search_engine_optimization/b2c_dynamic_mappings.html
Hope this helps.
I believe you'll likely need to do some path.resolve() magic in either your import statement or your webpack.config.js file as is shown in the accepted answer to this question: Set correct path to lazy-load component using Webpack - ES6
We did it in a different way. That required two steps
From within the template file add a script tag that creates a global variable for the static path. Something like
// inside .isml template
<script>
// help webpack know about the path of js scripts -> used for lazy loading
window.__staticPath__ = "${URLUtils.httpsStatic('/')}";
</script>
Then you need to instruct webpack to know where to find chunks by changing __webpack_public_path__ at runtime
// somewhere in your main .js file
// eslint-disable-next-line
__webpack_public_path__ = window.__staticPath__ + 'js/';
Optional step:
You might also want to remove code version from your __staticPath__ using replace (at least we had to do that)
__webpack_public_path__ = window.__staticPath__.replace('{YOUR_CODE_VERSION_GOES_HERE}', '') + 'js/';

Reading a JSON file from the create-react-app Public folder [duplicate]

This question already has answers here:
Fetch local JSON file from public folder ReactJS
(5 answers)
Closed 1 year ago.
I have a ipAddress.json file that has the contents:
{
"ipAddress": "11.111.111.111"
}
In the public folder i put that ipAddress.json file into an "ipAddress" folder so the path looks like "public/ipAddress/ipAddress.json"
But I cannot read this file. I am trying
const ipAddress = (require(process.env.PUBLIC_URL + '/ipAddress/ipAddress.json')).ipAddress;
using "json-loader" common library.
How do I get this to work? According to (Using the Public Folder) it should work just fine.
But I get this error:
Module not found: You attempted to import /ipAddress/ipAddress.json
which falls outside of the project src/ directory. Relative imports
outside of src/ are not supported.
Thank you for any help
If its just a json object you should be able to create a js file with the data inside a const object. Then export the const as a module.
New JS file to create:
const ipAddressJson = {
ipAddress: "11.111.111.111"
};
module.exports = ipAddressJson;
Inside the file you want the json object:
import ipAddressJson from 'path-to-the-js-file-above';
https://codesandbox.io/embed/tender-bash-2hjei
Why not put your JSON files into your project scope?
For example, if you have created the react app using create-react-app, the src folder will be the default project scope.
Put your JSON files into some folder like src/data and simply:
import data from '../data/somefile.json

what is use of require('.') in node.js

I was reading a node.js cli module documentation and it has one line like this. I know that we can include external modules like this but dont know what is the use of '.' while requiring a module;
const foo = require('.');
Can anyone tell me what is use of it or why its used that way.
It will import index file in the folder where you are running your file will empty require statement. Javascript require module will try to find index.js file if you do not specify any file name(only provide folder reference) in the require() argument.
Basically it's an alias for const foo = require('./index.js');
index.js
module.exports = 1;
foo.js
const foo = require('.');
console.log({ foo });
If both files are in the same folder then it will print
{ foo: 1 }
In require('.'), '.' represent the current directory, and ".." means parent directory.
-- parent
-- child1
-- grandchild1
-- grandchild2
-- child2
Now, suppose you are at child1 and want to import files from grandchild1 or inside the subfolder, Then you have to start from the current location (".") to the grandchild location.
require('./grandchild1/filename')
and, if need to import from the parent or outside your current directory, then you have to start backward that is from parent location (".."):
require('../parent/filename')
// here '..' take you one folder back (parent folder) and if you want to go one more folder back (parent of parent folder) then add one more pair of dots : '../../some_folder'

Categories

Resources