How to use dependency javascript in main application without having to copy scripts and imports?

Hi, I am new to Phoenix/Elixir so it might be that I just don’t know enough and I would apprecieate if someone could point me in the right direction.

I have an in-house developed library which contains a collection of useful modules to be used on frontend.
Some of the modules implement their own JavasSript and css.

Currently if we want to use the functionality of the library, those js and css files seem to have to be manually imported in our app.js.

Is there a way to avoid the manual path linking?

Hello and welcome,

Files imported in app.js are meant to be processed by webpack. It does not have to be and You could put those files in assets/static. They will be copied by copy-webpack-plugin and served by plug static.

Just to make sure I understood you correct. The js files should be placed in assets/static/js/ directory within the library?

Followup question:
The js is triggered by a hook, which must be specified in the app.js too. That still has to be done right?

The js in assets/static/js, the css in assets/static/css. But You decide how You organize your assets/static.

If You use it in hooks, then You need to have them available in app.js.

In that case it is different, and I would import them in app.js, just to have them available in it…

Thank you! I just thought there might be a more elegant solution :slight_smile:
On a related note. We have also noticed that if the library depends on node_module dependency assets (e.g. node_modules/bootstrap-icons, we need to place it within the developed-application directory or as an umbrella app.

If we link to it and it is outside the dev-app directory, the pathing to the asset won’t work.

Do you know if there might be a workaround for that?

You can import js from anywhere, even from other site (some restriction apply), given you have <script type="module" src="/js/app.js"></script> for your top level js.
The caveat is it does not work with IE:"module"

Thank you derek, I understand that. However that assumes I will always manually add or c/p the tag which is the exact thing I am trying to avoid.
It is not a problem to hammer something down to work, rather to do it nicely so that the hammer is not needed :wink:

You add one tag in html, pointing to your app.js. in your app.js you import everything you need, which can be anywhere as long as the browser can load them. A bundler is not strictly necessary. However, you may still want to conform to the existing path structure of npm packages. package.json 's dependencies hash support git, github, local path, in addition to the registry:

Just like mix in elixir. You can make an unpublished npm package so npm will fetch it and put it where it should be, under node_modules

1 Like