Import JS file placed in /public into JS file in /src - javascript

I am currently working on implementing OAuth authentication into my Vue app.
The authentication logic consists out of two files, the src/auth.js and public/silent-renewal.html. The first file contains all the logic to interact with the OAuth server. The second file is used to process the callback when the access token is renewed in the background.
In addition to these two files there is the file public/oidc-settings.js. This file contains a JSON variable defining the settings for the OAuth server.
It defines a JSON variable with the settings and a method to access them:
const settings = {
authority: 'http://localhost:8180/auth/realms/auth-example',
client_id: 'webclient-service',
redirect_uri: 'http://localhost:8080/callback',
response_type: 'code',
response_mode: 'query',
scope: 'openid profile',
post_logout_redirect_uri: 'http://localhost:8080/logout',
silent_redirect_uri: 'http://localhost:8080/silent-renewal.html',
automaticSilentRenew: true,
filterProtocolClaims: true,
loadUserInfo: true
}
function getSettings () {
return settings
}
In the silent-renewal.html file I access the settings by importing them with a script tag (<script src='oidc-settings.js'></script.
The problem is that I don't know how to access the oidc-settings.js from my auth.js. Currently I define the exact same settings again in the auth.js file.
How can I import a Javascript file placed in the public folder of my application into a Javascript file in the src folder?

If you're asking how you can navigate into a different folder, you can navigate up one level of a folder using ../.
It would look like this: '../public/your-file.js'
If you need to navigate up two (or more), just add another ../ for each level like this '../../folder/file.js'

You are trying to import something that is not set to be imported, probably your path is correct but you need to make the function that returns the configuration accessible to be imported.
Just change your settings file , so your function getSetting can be imported
export const getSettings = () => {
return settings
}
then in your "src" file just
import { getSettings } from '../public/../../'

Related

How to create a dynamic url with the # symbol

How would I create a dynamic route in Next.js with the # symbol?
For example localhost:3000/#some_username
I know you can create dynamic routes within the pages folder but how would I do it with just the # symbol and no / afterward like the above example.
You can add a prefix by defining a rewrite in your next.config.js.
module.exports = {
async rewrites() {
return [
{
source: '/#:username',
destination: '/users/:username'
}
]
}
}
This redirects all /#{username} routes to /users/{username}.
Some more information about rewrites in nextjs can be found here
It's the same as the standard dynamic routing in Next.js. You don't need rewrites.
Name the file or folder [#:username] in your root directory.
There are a few ways to do this:
App directory as folder named [#:username]
/app/[#:username]/page.js
Pages directory as file named [#:username].js
/pages/[#:username].js
Pages directory as folder named [#:username]
/pages/[#:username]/index.js
The param can be access the query param on the page like
import { useRouter } from "next/router";
const { query } = useRouter();
const username = query["#:username"];

laravel 8 include certain javascrip file into other js file

I have two files, one is my main js file called app.js and I have a file where I store all my js functions, called functions.js. As you can see on the image below.
But I want to include the functions.js file into the app.js file. So I googled on how to do it and this is what people said:
But my npm run dev says the file doesn't exist. But the path is correct. What am I doing wrong here, is there a other way to do it?
You can simply just create the file wherever you want to create it, and then export some properties or methods, and then import them in your app.js file, or in whatever file you need. Something like this :
//new_file.js
export const jokes = function() {
return ['funny', 'not really funny', 'boring']
}
export const heading = 'some global heading to be reused.'
And in your app.js file :
import { jokes, heading } from 'new_file.js'//specify actual path here .
console.log(jokes) // ['funny', 'not really funny', 'boring']
console.log(heading)//some global heading to be reused.
This tutorial might be helpful too .
http://www.2ality.com/2014/09/es6-modules-final.html

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

Implement with cypress with page object model

I'm trying to create cypress test project which support page object model.
I have created a new folder 'pageobject' at ../integration and there I have implemented LoginPageAdminPortal.js file as a page object class.
Code is like below,
export class LoginPageAdminPortal
{
visitLoginPageAdminPortal()
{
cy.visit (cypress.env('ADMIN_PORTAL_LOGIN_URL'))
}
loginAdminPortal()
{
cy.get('input[name=usernameUserInput]').type(cypress.env('ADMIN_USER_NAME'))
cy. get('input[name=password]').type(cypress.env('ADMIN_USER_PASSWORD'))
cy.contains('Continue').click()
return this
}
}
Then I wrote a test script for user login and the test sript locate at integration folder.
import {LoginPageAdminPortal} from '/pageobject/'
describe('Admin portal login with username and password', () => {
it ('Visit to the admil poratl login page', () => {
const loginPage = new LoginPageAdminPortal()
loginPage.visitLoginPageAdminPortal()
})
})
But at the compilation time I'm getting error like,
Error: Cannot find module '../pageobject/' from ' /home/achini/projects/cloudtest/cypress/cypress-iam-ui-test/iam-cypress-ui-test/cypress/integration'
Do I have to configure the pageobject module some other file. Any idea to solve this and successfully implement cypress with page object model.
folder structure
reference :
https://www.youtube.com/watch?v=5ifXs65O36k
https://www.youtube.com/watch?v=hMiBundGmNA
Imports are relative to the test which is in the integration folder, so you want
import { LoginPageAdminPortal } from './pageobject/LoginPageAdminPortal';
Please check out these two repositories where I implemented an example of the PO pattern. In one repository, I did it with TypeScript, and in the other one, I did it with JavaScript.
https://github.com/antonyfuentes/cypress-typescript-page-objects
https://github.com/antonyfuentes/cypress-javascript-page-objects
I think a good practice is to keep the integration folder only with your tests files. You can move the pageobject folder under support and use
import LoginPageAdminPortal from '../../support/PageObjects/LoginPageAdminPortal'in order to access the file.

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/';

Categories

Resources