How to use a javascript script file with phoenix

I’m trying to add a javascript script file like:

<script src="<%= Routes.static_path(@conn, "/js/main.min.js") %>"></script>

to a custom template (doesn’t have the app layout) I have the file in assets/js folder but when trying to access it in localhost like: localhost:4000/js/main.min.js it doesn’t exist.

Is there some configuration I should do in webpack to make it available?

You might have a line like this in webpack.config.js

new CopyWebpackPlugin([{ from: 'static/', to: './' }]),

More or less, files from assets/static are moved to priv/static.

So You should move the file from assets/js to assets/static if You want it to be copied and available in priv/static. Or move the file to assets/static/js/ if You want it to be available as priv/static/js/…

I copied the main.min.js to assets/static and I can see that it generates it inside priv/static, but when I go to the page landing.html.eex is still giving the following:

GET /main.min.js
[debug] ** (Phoenix.Router.NoRouteError) no route found for GET /main.min.js (PelableWeb.Router)
    (pelable) lib/phoenix/router.ex:324: PelableWeb.Router.call/2
    (pelable) lib/pelable_web/endpoint.ex:1: PelableWeb.Endpoint.plug_builder_call/2
    (pelable) lib/plug/debugger.ex:122: PelableWeb.Endpoint."call (overridable 3)"/2
    (pelable) lib/pelable_web/endpoint.ex:1: PelableWeb.Endpoint.call/2
    (phoenix) lib/phoenix/endpoint/cowboy2_handler.ex:40: Phoenix.Endpoint.Cowboy2Handler.init/2
    (cowboy) /home/csisnett/programming/pelable/code/deps/cowboy/src/cowboy_handler.erl:41: :cowboy_handler.execute/2
    (cowboy) /home/csisnett/programming/pelable/code/deps/cowboy/src/cowboy_stream_h.erl:296: :cowboy_stream_h.execute/3
    (cowboy) /home/csisnett/programming/pelable/code/deps/cowboy/src/cowboy_stream_h.erl:274: :cowboy_stream_h.request_process/3
    (stdlib) proc_lib.erl:249: :proc_lib.init_p_do_apply/3

Your endpoint has something like this in the Plug.Static part…

    only: ~w(css fonts images js uploads favicon.ico robots.txt)

You should put the file in assets/static/js/ and access it as /js/main.min.js

or add main.min.js to only: option of your endpoint.

1 Like

I moved it back to /js and that worked thank you!