點燈坊

失くすものさえない今が強くなるチャンスよ

Installing Alpine by NPM

Sam Xiao's Avatar 2022-10-05

Although we can use CDN to run Alpine, we can also use NPM to install Alpine locally under the node_modules folder.

Version

Alpine 3.10

Install Alpine

$ npm install alpinejs

Use NPM to install Alpine locally under the node_modules folder.

CDN

npm000

The classical counter is running.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="./node_modules/alpinejs/dist/cdn.min.js" defer></script>
    <title>Alpine</title>
  </head>
  <body>
    <body x-data="{ count: 0 }">
      <button @click="count++">+</button>
      <span x-text="count" />
    </body>
  </body>
</html>

Line 6

<script src="./node_modules/alpinejs/dist/cdn.min.js" defer></script>

Just mount CDN on <script> :

  • cdn.min.js:Alpine is located under the node_modules folder
  • defer : make Alpine execute after HTML content is parsed

ES Module

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script type="module">
      import Alpine from './node_modules/alpinejs/dist/module.esm.js'
      Alpine.start()
    </script>
    <title>Alpine</title>
  </head>
  <body>
    <body x-data="{ count: 0 }">
      <button @click="count++">+</button>
      <span x-text="count" />
    </body>
  </body>
</html>

Line 6

<script type="module">
  import Alpine from './node_modules/alpinejs/dist/module.esm.js'
  Alpine.start()
</script>
  • Import Alpine by ES module
  • module.esm.js:Alpine is located under the node_modules folder
  • We have to use Alpine.start() to initialize Alpine

Conclusion

  • If we want to use many packages with Alpine, we can also use NPM to install Alpine under the node_modules folder

Reference

Alpine, Installation