npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

asset_import_hook

v0.4.10

Published

AssetImport Phoenix LiveView hook for dynamic asset loading

Downloads

3

Readme

AssetImport

Webpack asset imports directly in Elixir code. For example in Phoenix controllers/views/templates or LiveView's.

Features

  • Only load assets that are used for current render.
  • Helps to avoid assets over, under, or double fetching.
  • Optimal asset packaging and cache reuse with Webpack code splitting.
  • Supports Phoenix LiveView's by loading assets dynamically.
  • Supports mix dependencies that are using asset_import.

Installation

The package can be installed by adding asset_import to your list of dependencies in mix.exs:

def deps do
  [
    {:asset_import, "~> 0.4.10"}
  ]
end

Usage

/* assets/css/forms.css */

form {
  /* a lot of form styling, or import bootstrap `_forms.scss` etc */
}
// assets/js/login_form.js

import "../css/forms.css"

// some login form specific javascript here

Anywhere in your views, templates, or LiveView renders:

<div>
  <%= if @logged_in do %>
    <div>My profile..</div>
  <% else %>
    <!--
    You can use <% asset_import @conn, "js/login_form" %> (without =),
    if you are not using this template in LiveView. It will save some bytes from your html.
    -->
    <%= asset_import @conn, "js/login_form" %>
    <!--
    Inside LiveView use @socket instead @conn
    -->
    <%= asset_import @socket, "js/login_form" %>
    <form>Login form..</form>
  <% end %>
</div>

Usage with LiveView hooks that guarantees that code is always loaded before hook usage:

<div>
  <%= if @logged_in do %>
    <div>My profile..</div>
  <% else %>
    <form data-hook="MyHook" phx-hook="AssetHook" data-assets="<%= asset_hook(@socket, "js/myHook") %>">
      Login form..
    </form>
  <% end %>
</div>

Assets js/login_form.js and css/forms.css are only loaded when user is not logged in.

Setup

1. Configuration

Typical asset_import config:

# config/config.exs

config :asset_import, MyAppWeb.Assets,
  assets_base_url: "/",
  assets_path: Path.expand("assets"),
  manifest_path: Path.expand("priv/static/manifest.json"),
  entrypoints_path: Path.expand("assets/entrypoints.json")

Replace phoenix watcher from webpack to nodemon:

# config/dev.exs

config :my_app, MyAppWeb.Endpoint,
  debug_errors: true,
  code_reloader: true,
  check_origin: false,
  watchers: [node: ["node_modules/nodemon/bin/nodemon.js", cd: Path.expand("../assets", __DIR__)]]

Disable entrypoints file generation in test.

# config/test.exs

config :asset_import, entrypoints_path: :disabled

2. Create an assets module

defmodule MyAppWeb.Assets do
  use AssetImport,
    assets_path: "assets" # optional, defaults to "assets"
  use AwesomeUiComponents.Assets # add dependency assets
end

3. Use your assets module in web module

defmodule MyAppWeb do
  ..
  def view do
    quote do
      ..
      use MyAppWeb.Assets
      ..
    end
  end
  ..
end

4. Import file macros to your layout view

defmodule MyAppWeb.LayoutView do
  use MyAppWeb, :view
  import MyAppWeb.Assets.Files
end

5. Add scripts and styles to layout

<!-- Content rendering has to execute before scripts and styles -->
<% body = render "body.html", assigns %>

<html>
  <head>
    
    <!-- Styles for current page (render blocking) -->
    <%= asset_styles() %>

    <!-- Optional: Preload unused styles and scripts -->
    <%= preload_asset_styles() %>
    <%= preload_asset_scripts() %>

  </head>
  <body>
    <%= body %>

    <!-- Scripts for current page -->
    <%= asset_scripts() %>

  </body>
</html>

Or

<!-- Content rendering has to execute before scripts and styles -->
<% body = render "body.html", assigns %>

<html>
  <head>
    

    <!-- Styles for current page (render blocking) -->
    <%= for path <- asset_style_files() do %>
      <link rel="stylesheet" href="<%= path %>" />
    <% end %>

    <!-- Optional: Preload unused styles and scripts -->
    <%= for path <- unused_asset_style_files() do %>
      <link rel="preload" href="<%= path %>" as="style">
    <% end %>
    <%= for path <- unused_asset_script_files() do %>
      <link rel="preload" href="<%= path %>" as="script">
    <% end %>

  </head>
  <body>
    <%= body %>

    <!-- Scripts for current page -->
    <%= for path <- asset_script_files() do %>
      <script type="text/javascript" src="<%= path %>"></script>
    <% end %>

  </body>
</html>

6. Add LiveView hook (only when LiveView is used)

import LiveSocket from "phoenix_live_view"
import Socket from "phoenix"
import AssetImport from "asset_import_hook"

let liveSocket = new LiveSocket("/live", Socket, { AssetImport })
liveSocket.connect()

7. Webpack setup

Copy example_assets/* to your project assets or adjust existing files manually:

  • // assets/nodemon.json
    {
      "watch": ["entrypoints.json", "webpack.config.js"],
      "exec": "node_modules/webpack/bin/webpack.js --color --mode development --watch-stdin"
    }
  • // assets/package.json
    {
      ..
      "dependencies": {
        ..
        "asset_import_hook": "0.4.10" // only when LiveView is used
        ..
      },
      "devDependencies": {
        ..
        "nodemon": "1.19.2",
        "uglifyjs-webpack-plugin": "2.2.0",
        ..
      }
    }
  • // assets/webpack.config.js
    ..
    
    8: const entrypoints = require('./entrypoints.json') || {};
    9:
    10: if (Object.keys(entrypoints).length === 0) {
    11:   console.log('No entrypoints');
    12:   process.exit();
    13:   return;
    14: }
    
    ..
    
    23:    runtimeChunk: 'single',
    24:    chunkIds: 'natural',
    25:    concatenateModules: true,
    26:    splitChunks: {
    27:      chunks: 'all',
    28:      minChunks: 1,
    29:      minSize: 0
    30:    }
    31:  },
    32:  entry: entrypoints,
    33:  output: {
    34:    filename: 'js/[id]-[contenthash].js',
    35:    chunkFilename: 'js/[id]-[contenthash].js',
    36:    path: path.resolve(__dirname, '../priv/static')
    37:  },
    38:  plugins: [
    39:    new MiniCssExtractPlugin({
    40:      filename: 'css/[id]-[contenthash].css',
    41:      chunkFilename: 'css/[id]-[contenthash].css',
    42:    }),
    43:    new ManifestPlugin({ fileName: 'manifest.json' }),
    
    ..