Create-react-app: Access PUBLIC_URL in js files

Created on 28 Aug 2017  Â·  9Comments  Â·  Source: facebook/create-react-app

I need to have some widget.js in public folder. This file will create iframe and init my React app into this iframe. To do this manipulation I need access to a %PUBLIC_URL% property but looks like it works only for .html files. There is some way to solve this?

proposal

All 9 comments

process.env.PUBLIC_URL 😄

@Timer my file are located in public folder:

Uncaught ReferenceError: process is not defined
at widget.js:1

Oops, my mistake! There's currently no way to use this in other files. For now, I'd suggest a custom script which performs this interpolation for you.

@Timer can you help me with implementing this with yarn eject?

@fantua haven't tested it, but maybe adding this to your index.html works?

<script>
window.PUBLIC_URL = "%PUBLIC_URL%"
</script>

and access it from your widget.js

someFunction(window.PUBLIC_URL)

it's attached to window object though, so... ¯\_(ツ)_/¯

Yep, that should work.

@viankakrisna thx, but widget.js is standalone script and wouldn't be inited in index.html.

My solution is extra-entry-webpack-plugin, this extra entry allow me to create widget.js in root of build and process it like a default create-react-app .js file.

thx, but widget.js is standalone script and wouldn't be inited in index.html.

Not sure what this means. If you put the <script> injecting the variable first, the variable will be accessible by the time widget.js runs. This assumes widget.js is under your control. But if it isn’t, how could you possibly read something in it anyway?

widget.js wouldn't be putted in index.html or any other .html file from public folder. It's standalone script, that will be placed in any website to init iframe with my React app. To do this widget.js must have access to a process.env.PUBLIC_URL for setting source of iframe.. ¯(ツ)/¯

I hope now it's correct explanation.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

gaearon picture gaearon  Â·  85Comments

riceyeh picture riceyeh  Â·  116Comments

akctba picture akctba  Â·  80Comments

andreypopp picture andreypopp  Â·  96Comments

benneq picture benneq  Â·  99Comments