配置 Webpack 以在 Laravel 应用程序中工作

Configuring Webpack to work in a Laravel application

我想将 webpack-dev-server 用于我的基本 Laravel 应用程序。从 official Webpack docs 我了解到以下内容:

You may want to run a backend server or a mock of it in development. You should not use the webpack-dev-server as a backend. Its only purpose is to serve static (webpacked) assets.

You can run two servers side-by-side: The webpack-dev-server and your backend server.

在页面底部,他们给出了一个如何完成该操作的示例。我跟进并遇到了两条错误消息。这是我将 Webpack 集成到 Laravel 应用程序中的尝试。

webpack.config.js

var path = require("path");

module.exports = {
    context: path.resolve('resources'),
    entry: [
        './assets/js/app.js'
    ],
    output: {
        path: path.resolve('public/assets/'),
        publicPath: 'http://localhost:8080/assets/',
        filename: "bundle.js"
    },
    devServer: {
        contentBase: 'public',
        hot: true,
        proxy: {
            "*": "http://laravel.dev/"
        }
    }
};

app.blade.php

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Learning Laravel</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>

<body>
    <div class="container">
        @yield('content')
    </div>

    @yield('footer')
    <script src="http://localhost:8080/assets/bundle.js"/>
</body>

</html>

vagrant@learning-laravel:~/learning-laravel$ webpack-dev-server --inline

控制台输出:

http://localhost:8080/
webpack result is served from http://localhost:8080/assets/
content is served from public
Hash: 3346964212f5b22513c6
Version: webpack 1.12.2
Time: 347ms
    Asset    Size  Chunks             Chunk Names
bundle.js  228 kB       0  [emitted]  main
chunk    {0} bundle.js (main) 213 kB [rendered]
    [0] multi main 52 bytes {0} [built] [1 error]
    [1] /usr/lib/~/webpack-dev-server/client?http://localhost:8080 2.14 kB {0} [built]
    [2] (webpack)/~/node-libs-browser/~/url/url.js 22.3 kB {0} [built]
    [3] (webpack)/~/node-libs-browser/~/punycode/punycode.js 14.6 kB {0} [built]
    [4] (webpack)/buildin/module.js 251 bytes {0} [built]
    [5] (webpack)/~/node-libs-browser/~/url/~/querystring/index.js 127 

...

   [61] ./resources/assets/js/app.js 103 bytes {0} [built]
   [62] ./resources/assets/js/login.js 28 bytes {0} [built]

ERROR in multi main
Module not found: Error: Cannot resolve module 'webpack/hot/dev-server' in /home/vagrant/learning-laravel/resources
 @ multi main
webpack: bundle is now VALID.

我正在使用 Homestead。该应用程序在 http://laravel.dev/ 上送达。所以我的问题是如何 运行 两个服务器(webpack-dev-server 和后端服务器)并排。我错过了什么?

您缺少的很简单,您必须在 Laravel 后端服务器(例如路由 /assets)下代理 webpack-dev-server。

要做到这一点,我让你检查 http-proxy、Express 中间件,甚至 socat / netcat CLI 工具。