How to import AlpineJS with NPM?

Viewed 4200

How is one supposed to import AlpineJS with NPM?

The AlpineJS docs say:

From npm: Install the package from npm.

npm i alpinejs

Include it in your script.

import 'alpinejs'

I put that last line into one of my JavaScript files. Nothing happened though. I figured, maybe I need a bundler like Grunt to make that import actually do something. I wouldn't know how the client should otherwise know that 'alpinejs' refers to alpine.js in node_modules/alpinejes/dist. Grunt just lets the line stand as it is and doesn't the AlpineJS file to my output directory.

What I want to achieve:

  • Use AlpineJS in the client, without being dependent on the CDN
  • Possibly: concatenating alpine.js with other script files to reduce the number of server requests
2 Answers

You need a bundler that supports npm modules/imports to process your JS file (that includes the Alpine.js import). Webpack, rollup or parcel should all do the job.

Otherwise yes, you could concatenate the Alpine.js file at node_modules/alpinejs/dist/alpine.js with your JS file and use that (at which point you don't need the import statement)

Option one

import Alpine from 'alpinejs'
window.Alpine = Alpine
Alpine.start();

Best option for me

import Alpine from 'alpinejs';
window.Alpine = Alpine;
queueMicrotask(() => {
    Alpine.start()
});
Related