首页 > 解决方案 > React - PUBLIC_URL 设置后仍未定义

问题描述

我尝试为我的 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}
}

我什至创建了一个.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);
            }
        });
    }
}

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

标签: node.jsreactjsenvironment-variables

解决方案


推荐阅读