【问题标题】:Replacing variable with @rollup/plugin-replace throws error用 @rollup/plugin-replace 替换变量会引发错误
【发布时间】:2022-01-15 13:38:42
【问题描述】:

问题

我正在尝试使用 @rollup/plugin-replace 注入/替换环境变量。不幸的是,我收到了这个错误:

TypeError: 无法将 undefined 转换为对象

代码

// rollup.config.js
import replace from "@rollup/plugin-replace";
import { config } from "dotenv";
config();

export default {
  // ...
  plugins: [
    replace({
      values: { YOUTUBE_API: JSON.stringify(process.env.YOUTUBE_API) },
      preventAssignment: true,
    }),
  // ...
}

我这样称呼它:

  onMount(() => {
    (async function getPopular() {
      videos = await axios.get("https://www.googleapis.com/youtube/v3/videos", {
        part: "id, snippet, suggestions",
        chart: "mostPopular",
        key: YOUTUBE_API,
      });
    })();
  });

我尝试了什么

我注销了变量,因此可以确认它存在。另外,如果我删除 stringify 函数,我会收到另一个错误:

ReferenceError: blablabblub 未定义

我已经在其他项目中成功地做到了这一点。这到底是怎么回事?

【问题讨论】:

    标签: javascript svelte rollup rollupjs svelte-3


    【解决方案1】:

    所以在对同样的问题进行了一些研究之后,我发现它与对象分配有关。例如:

    export default {
      // ...
      plugins: [
        replace({
          values: {
            env: {
              API_URL: process.env.API_URL,
              API_VERSION: process.env.API_VERSION,
            }
          },
          preventAssignment: true,
        }),
      // ...
    }
    
    
    // in some JS or Svelte file
    const config = {
        host: env.API_URL,
        version: env.API_VERSION
    }
    
    // The above will result in a reference error of 'env' not being defined. 
    
    // in the same JS or Svelte file..
    const envVars = env;
    const config = {
        host: envVars.API_URL,
        version: envVars.API_VERSION
    }
    
    // this works just fine!
    
    

    我没有更多时间进行调查,但我的直觉是,当变量名嵌套在对象赋值中时,汇总不会替换变量名。可选标志允许这样做可能很好,但它也可能会变得非常混乱,因此他们为什么不这样做。

    如果这对您来说仍然是个问题,我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2012-03-14
      • 1970-01-01
      • 2022-12-10
      • 2020-07-13
      • 2011-09-29
      • 2020-05-10
      • 2019-01-21
      • 1970-01-01
      • 2023-02-20
      相关资源
      最近更新 更多