温馨提示×

centos上laravel如何进行代码热更新

小樊
38
2025-12-11 12:35:23
栏目: 智能运维

在CentOS上,Laravel代码热更新可以通过使用Laravel Mix的watch命令来实现。以下是详细步骤:

1. 安装Laravel Mix

首先,确保你已经安装了Laravel Mix。如果还没有安装,可以通过以下命令进行安装:

npm install laravel-mix --save-dev

2. 配置Laravel Mix

在你的项目根目录下找到webpack.mix.js文件,并进行相应的配置。例如:

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

mix.js('resources/js/app.js', 'public/js')
   .sass('resources/sass/app.scss', 'public/css');

3. 启动热更新

在项目根目录下运行以下命令来启动热更新:

npm run watch

这个命令会监视你的JavaScript和Sass文件的变化,并在检测到变化时自动重新编译。

4. 配置Nginx或Apache

为了确保热更新能够正常工作,你需要配置Nginx或Apache以支持WebSocket连接。以下是Nginx的示例配置:

server {
    listen 80;
    server_name yourdomain.com;

    root /path/to/your/laravel/project/public;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # 根据你的PHP版本调整
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location /socket.io/ {
        proxy_pass http://localhost:3000; # 假设你的Laravel Mix运行在3000端口
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
    }
}

5. 启动Laravel Mix热更新服务器

如果你使用的是Laravel Mix的开发服务器,确保它运行在支持WebSocket的端口上。默认情况下,Laravel Mix的开发服务器运行在http://localhost:3000

npm run watch -- --host 0.0.0.0 --port 3000

6. 配置Laravel Echo Server(可选)

如果你使用Laravel Echo进行实时通信,还需要配置Laravel Echo Server。以下是安装和启动Laravel Echo Server的步骤:

npm install -g laravel-echo-server

然后,在项目根目录下创建一个laravel-echo-server.json文件,并进行配置:

{
  "authHost": "http://yourdomain.com",
  "authEndpoint": "/broadcasting/auth",
  "clients": [
    {
      "appId": "your-app-id",
      "key": "your-app-key"
    }
  ],
  "database": "mysql",
  "databaseConfig": {
    "mysql": {
      "host": "127.0.0.1",
      "port": "3306",
      "database": "your_database",
      "username": "your_username",
      "password": "your_password"
    }
  },
  "devMode": true,
  "host": null,
  "port": "3000",
  "protocol": "http",
  "socketio": {},
  "sslLocalCertificate": "",
  "sslPassphrase": "",
  "sslPort": "443",
  "sslCertChain": "",
  "sslKey": "",
  "subscribers": {
    "http": true,
    "redis": true
  },
  "apiOriginAllow": {
    "allowCors": false,
    "allowOrigin": "",
    "allowMethods": "",
    "allowHeaders": ""
  }
}

最后,启动Laravel Echo Server:

laravel-echo-server start

通过以上步骤,你应该能够在CentOS上实现Laravel代码的热更新。

0