create-react-app icon indicating copy to clipboard operation
create-react-app copied to clipboard

Importing a module from a js file in public folder

Open nickgieschen opened this issue 3 years ago • 1 comments

I have to include an external, minfied js module. E.g. "external/script.js".

Let's say, external/script.js is (it obviously isn't but...):

const mytest = "asdfasdf"
export default mytest

I have put external/script.js in my public folder.

In public/index.html I have:

<script type="module" src="%PUBLIC_URL%/external/script.js"></script>

How can I then import and use mytest in a regular react component? What is the import path I can use for this? I have looked into CRACO and excluding the ModuleScopePlugin, but I'm still not sure how to actually reference the module.

nickgieschen avatar Sep 29 '22 21:09 nickgieschen

You could use dynamic import() to import ES modules dynamically. The trick is to tell Webback not to convert dynamic import()s for it's own use (lazy loading, chunking):

import(/webpackIgnore: true/ 'path/to/module.js');

https://webpack.js.org/api/module-methods/#magic-comments

mikeaustin avatar Oct 03 '22 15:10 mikeaustin