Importing JS from node packages

Is there a good way to import JS from a Node package on build? I typically do this with Gulp now, but would like to automate it so that I don’t forget when building the site with the hugo command.

2 Likes

ug not a big fan of huge “npm installs” so I have spent a fair amount of time pondering on that question.

If you dependency and bundling requirements are simple (which I guess is a good goal to have), you can get far by wrapping your dependencies in Hugo Components, ref. an experiment I did last week:

Once these libs are mounted into your project (either directly or via a module path (see above)) they are managed by Hugo’s package manager, which is what NPM is dreaming to be when it grows up.

Once all of this matures I have some plans to create some “Hugo maintained” packages for what we/I consider useful libraries for Hugo.

We could imagine Hugo doing some NPM interaction in the future, but at the moment, for it to work with Hugo modules, you either need to mount the distribution on the library’s GitHub repo or maybe have your own GitHub repo with a node_modules and mount that into your project, as in https://github.com/bep/hugo-jslibs/blob/master/alpinejs/config.toml

2 Likes

So, this is speaking more to a local package that I’ve already brought in to node_modules, and not worried about fetching the package itself, but more concerned with importing those files at build time into Hugo.

For example, an npm package I have installed into node_odules has a *.js file that I want to include into Hugo’s /static folder, but I want it to constantly check for or import that file whenever I run the hugo command.

Possible? Or does your answer address this as well?

Yes that is possible. In your config:

[module]
  [[module.mounts]]
    source = "node_modules/somelibrary/dist"
    target = "static/somelibrary"

You can also mount to assets, content etc. and you can also mount single files not just directories.

When you’re running the server, the above directories will be added to the watch list for changes.

9 Likes

Awesome, thank you!

Don’t forget to mount the static folder if you use this method:

2 Likes