React - PUBLIC_URL 设置后仍然未定义

Fan*_*sia 5 environment-variables node.js reactjs

我尝试为我的 serviceworker 配置设置 PUBLIC_URL,并在捆绑应用程序之前在 webpack.config.js 中设置我的 PUBLIC_URL:

webpack.config.js

module.exports = (env) => {

    const isProduction = env.production === true;
    const isDevelopment = env.development === true;

    process.env.NODE_ENV = isProduction ? 'production' : isDevelopment && 'development';
    process.env.PUBLIC_URL = '/';

    return {...config}
}
Run Code Online (Sandbox Code Playgroud)

我什至创建了一个.env文件,PUBLIC_URL=/但当我在 service.worker 寄存器中记录 PUBLIC_URL 时,似乎没有任何效果,它仍然是未定义的:

export function register(config) {
    console.log(process.env.PUBLIC_URL)

    if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
        const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
        if (publicUrl.origin !== window.location.origin) {
            return;
        }

        window.addEventListener('load', () => {
            const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

            if (isLocalhost) {
                checkValidServiceWorker(swUrl, config);
                navigator.serviceWorker.ready.then(() => {
                    console.log(
                        'This web app is being served cache-first by a service worker.');
                });
            } else {
                registerValidSW(swUrl, config);
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用 webpack-dev-server 运行该应用程序,并通过生成 dist 文件夹并打开 index.html 文件夹来尝试它。有谁知道原因吗?