【问题标题】:how to replace strings with .env (dotenv-flow) with svelte-kit?如何用 .env (dotenv-flow) 用 svelte-kit 替换字符串?
【发布时间】:2021-07-24 20:05:41
【问题描述】:

svelte.config.js里面我有这个:

    preprocess: autoPreprocess({
        replace: [
            ['API_ENDPOINT', JSON.stringify(process.env.API_ENDPOINT)]
        ]
    }),

它应该替换字符串“API_ENDPOINT”,但不是。

这是我的使用方法:

async function api(url: string, body = {}, opts = {}) {
    const endpoint = 'API_ENDPOINT';
    console.log(endpoint);
    const res = await fetch(endpoint + url, {
        method: 'POST',
        headers: {
            'Content-type': 'application/json',
        },
        body: JSON.stringify(body)
    });

    if (!res.ok) {
        const err = await res.json();
        throw (err || res.statusText);
    }

    return opts.raw ? await res.text() : await res.json();
}

export default api;

我得到的只是http://localhost:3000/API_ENDPOINT/subscriptions

【问题讨论】:

    标签: sveltekit


    【解决方案1】:

    在您的 svelte.config.js 文件中,而不是

    autoPreprocess({
      replace: [['process.env.NODE_ENV', JSON.stringify(process.env.NODE_ENV)]],
    });
    

    使用

    import sveltePreprocess from 'svelte-preprocess'
    sveltePreprocess({
      replace: [['process.env.NODE_ENV', JSON.stringify(process.env.NODE_ENV)]],
    });
    

    在我看来,autoPreprocess 已被弃用,但 README 文档未正确更新。

    您可能还需要考虑执行以下操作之一:

    直接使用process.env.API_ENDPOINT
    const endpoint = process.env.API_ENDPOINT;
    
    创建一个单独的javascript函数来处理环境变量

    类似的东西

    envVars.js

    import dotenv from 'dotenv-flow';
    import path from 'path';
    
    dotenv.config({
      path: path.resolve(__dirname, `path-to-your-(.env)-file`),
    });
    
    export const getEnvVar = (key) => process.env[key];
    

    并像这样使用它:

    import { getEnvVar } from 'path-to-envVars'
    const endpoint = getEnvVar('API_ENDPOINT');
    
    如果您已经在使用 Vite 作为构建工具

    .env 文件中添加变量,如下所示:

    VITE_YOUR_ENV_VAR_GOES_HERE=bar
    

    在你的情况下:

    VITE_API_ENDPOINT=your_value
    

    然后将它们导入单独的 javascript 或 typescript 文件中

    envVars.js

    export const envVars = {
      API_ENDPOINT: import.meta.env.VITE_API_ENDPOINT
    };
    

    然后导入 envVars 并照此使用:

    import { envVars } from 'path-to-envVars.js'
    

    现在您可以像这样读取您的环境变量:

    envVars.myVariable 或者,在你的情况下 const endpoint = envVars.API_ENDPOINT

    【讨论】:

    • 我收到此错误:500 process is not defined config@http://localhost:3000/node_modules/.vite/dotenv-flow.js?v=d34d57c4:178:9 @http://localhost:3000/src/env.ts:2:10
    • export const getEnvVar = (key) => process.env[key]; 找不到process
    猜你喜欢
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    • 2019-09-12
    • 2013-08-17
    • 1970-01-01
    • 1970-01-01
    • 2016-05-27
    相关资源
    最近更新 更多