3

我的 webpack.config.js 中有 3 个条目,它们生成 3 个不同的 HTML 文件。我这样做是为了可以将它们托管在不同的域上:

现在我有一个自定义开发服务器,它启动 webpack 构建 3 次,以便我可以指出索引文件应该是什么。我想做的是将其更改为单个服务器并使用主机标头来决定要加载的索引文件。

我尝试这样做的方式是:

    devServer: {
        host: '0.0.0.0',
        /// Enable gzip
        compress: true,
        contentBase: './dist',
        /* Theoretically, the public option is better but they only support a single host
         *
         * This is a security issue not using public.
         * */
        disableHostCheck: true,

        // enable HMR on the server
        hot: true,
        overlay: true,
        after: (app) => {
            /* Server the dev settings that are normally injected via nginx */
            app.get('/settings.js', function(req, res) {
                const fullPath = path.join(__dirname, "settings.dev.js");
                res.sendFile(fullPath);
            });

            app.get('*', function(req, res, next) {
                const headers = req.headers;
                const host = headers['host'];

                if (
                    /* We only wan't to override GET */
                    (req.method !== 'GET') ||

                    /* They didn't send an accept header */
                    (!headers || typeof headers.accept !== 'string') ||

                    /* They prefer JSON */
                    (headers.accept.indexOf('application/json') === 0) ||

                    /* They don't want HTML */
                    (!acceptsHtml(headers.accept))
                ) {
                    console.log("TERMINATING EARLY", req.method, headers.accept);
                    return next();
                }

                let indexFile = 'index.html';

                switch(host) {
                    case "site":
                        indexFile = 'site.html';
                        break;
                    case "forms":
                        indexFile = 'forms.html';
                        break;
                }

                console.log("BEFORE REQ URL", req.url);
                req.url = `${indexFile}`;
                console.log("AFTER REQ URL", req.url);
                next();
            });

        },
    }

这适用于网站的初始加载,但我得到 404 用于其他所有内容。我应该做什么而不是req.url?我不能使用res.sendFile,因为 webpack 正在编译内存中的所有内容。

4

0 回答 0