Importing from node_modules with js.Build

Now that Hugo Pipes has JavaScript building via ESBuild, I’m wondering:

Is it possible, using js.Build in templates and import in JavaScript, to load js modules directly from node_modules?

Thanks!

1 Like

Answering to myself: yes, it’s possible! Path is relative to JS file, e.g.:

/assets/js/search.js:

import Fuse from "../../node_modules/fuse.js/dist/fuse.basic.esm.min.js";
import Mark from "../../node_modules/mark.js/dist/mark.es6.min.js";
...
const fuse = new Fuse();
...

/layouts/partials/scripts.html:

{{- $search := resources.Get "js/search.js" | js.Build (dict "minify" true "target" "es2015") | fingerprint -}}

All imports work perfectly, and the JS bundling is incredible fast (especially if compared with e.g. Babel)!

(Unfortunately, I couldn’t get moment.js to work with any locale via import, but this is not a Hugo problem, anyway.)

1 Like

Doing

import Fuse from "fuse"

Should work and would be more portable. Note that there are some path issues that we intend to fix (esp. when you’re using themes/theme components).

But I agree, it’s incredibly fast and cool.

4 Likes

Thank you, @bep, for the explanation and for Hugo!

2 Likes

By the way, the method suggested by @bep happens to make moment.js work with locales:

import moment from "moment";
import "moment/locale/pt-br";
moment.locale("pt-BR"); /* or moment.locale(document.querySelector("html").lang); */
moment();
...
2 Likes

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.