【问题标题】:How to Hide API key in Preact?如何在 Preact 中隐藏 API 密钥?
【发布时间】:2022-01-02 04:30:11
【问题描述】:

如何在 preact 中隐藏 api 密钥,在 react 中我使用了 .env 文件,但不知道如何在 preact 中执行?

index.js?2e9b:8 Uncaught (in promise) ReferenceError: process is not defined
    at eval (index.js?2e9b:8)
    at Generator.next (<anonymous>)
    at asyncGeneratorStep (index.js:5)
    at _next (index.js:7)
    at eval (index.js:7)
    at new Promise (<anonymous>)
    at eval (index.js:7)
    at getSeriesInfo (index.js?2e9b:7)
    at Object.eval [as __] (index.js?2e9b:14)
    at j (index.js?a178:361)

【问题讨论】:

    标签: api process environment-variables preact


    【解决方案1】:

    Preact 只是一个 UI 库,但我假设您指的是 Preact-CLI,它是一个实际的构建工具。如果这不正确,请告诉我。

    我们的 wiki 在“Use Environment Variables in your Application”下对此进行了介绍。 process 将不存在于 Node 之外,因此您需要使用 DefinePlugin 指定要使用的变量。

    将以下内容添加到您的 preact.config.js 文件中:

    export default (config, env, helpers) => {
        config.plugins.push(
            new helpers.webpack.DefinePlugin({
                'process.env.MY_VARIABLE': JSON.stringify('my-value'),
            }),
        );
    };
    

    如果您特别想从.env 文件中读取,您还需要添加一些实用程序来读取它,例如dotenv

    import dotenv from 'dotenv';
    
    dotenv.config();
    
    export default (config, env, helpers) => {
        config.plugins.push(
            new helpers.webpack.DefinePlugin({
                'process.env.MY_VARIABLE': JSON.stringify(process.env.MY_VARIABLE),
            }),
        );
    };
    

    【讨论】:

      最近更新 更多