如何设置 Alpine.js 3 与 mix

How to set up Alpine.js 3 with mix

我在新项目中开始使用 Alpine.js v3 时遇到问题。这是我的 package.json 和 Alpine 设置:

  "devDependencies": {
    "laravel-mix": "^6.0.19"
  },
  "dependencies": {
    "alpinejs": "^3.0.6"
  }
import Alpine from 'alpinejs'

window.Alpine = Alpine
window.Alpine.start()

Alpine.data('demo', () => ({
    open: false,

    toggle() {
        this.open = !this.open
    }
}))

驱动此标记:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Demo</title>
    <script src="assets/app.js"></script>
  </head>
  <body>
    <div x-data="demo">
      <button @click="toggle">Expand</button>

      <div x-show="open">Content...</div>
    </div>
  </body>
</html>

然后我使用 laravel-mix:

构建我的 javascript
// webpack.mix.js

let mix = require('laravel-mix');

mix
    .setPublicPath('public')
    .js('src/app.js', 'public/assets');

javascript 构建良好并且页面加载没有错误,但是当我单击切换按钮时,内容会按预期展开,但我在浏览器控制台中收到以下错误并且内容不会在后续点击时隐藏。

Uncaught (in promise) TypeError: i is not a function app.js:2282:28

如果我推迟我的脚本或将它移到底部,页面在加载时会损坏,我会得到以下信息:

Uncaught TypeError: undefined is not a non-null object app.js:1995:12

任何人都可以帮助我修复我的设置吗?

很可能您只是忘记将 defer 属性添加到 script 标签

<script defer src="assets/app.js"></script>

但也作为文档 says

If you imported Alpine into a bundle, you have to make sure you are registering any extension code IN BETWEEN when you import the Alpine global object, and when you initialize Alpine by calling Alpine.start().

所以将脚本更改为

import Alpine from 'alpinejs';

Alpine.data('demo', () => ({
    open: false,

    toggle() {
        this.open = !this.open
    }
}));

window.Alpine = Alpine;

// should be last
Alpine.start();

注意:如果出现 assignment to undeclared variable data 等错误,您可以将导入更改为 import Alpine from 'alpinejs/dist/module.cjs';