網站搜尋

javascript - 無法進入由 rollup plugin-replace 定義的物件


在一個 Svelte 元件中,我正在嘗試存取我在 rollup 配置檔中設定的物件。我的 rollup.config.js 檔案長這樣:

import replace from '@rollup/plugin-replace';

...
export default {
...
    replace({
        foo: JSON.stringify({ bar: 'Hello' }),
    }),

...

在我的 Svelte 組件中,一個簡單的 console.log(foo) 可以正常運作:

但是當我試圖進入那個 foo 物件,例如 console.log(foo.bar) 時,我得到 foo 未定義:

答案#1

好問題!對象 foo 仍然未定義,因此它拋出了正確的錯誤,並且無法找到 foo 以替換成你打算替換的內容。

解決方案是讓 replace 插件執行其工作。你可以在你的 js 或 .svelte 檔案中像這樣存取你的變數

const { bar } = foo;

console.log(bar);

注意:此插件有更改,詳情請查看此處。如果您打算使用 dotenv 的環境變數,請考慮

import { config } from "dotenv";

...
replace({
      values: {
        foo: JSON.stringify({ bar: "Hello", ...config().parsed }),
      },
    }),
...

以及在你的 svelte 檔案中

  const { bar, ...rest } = foo;
  console.log("bar=>", bar);
  console.log("env=>", rest);

答案#2

本文件的這一部分說明了您的具體問題。
https://github.com/rollup/plugins/tree/master/packages/replace#delimiters

delimiters 選項控制字串將如何被匹配。預設的 delimiters 為 ['\\b', '\\b(?!\\.)'],它只會替換那些前後都是單字邊界且後面不是點的 foo。因此,依照你的 rollup.config.js,行為將會是

console.log(foo)
// becomes
console.log({"bar":"Hello"})

console.log(foo.bar)
// is not replaced by the plugin as `foo` IS followed by a dot

console.log(foo['bar'])
console.log(foo .bar) // space after `foo`
// both satisfy the delimiter check again and print: Hello
// (horrible coding style in the latter but to illustrate how it works)

const { bar } = foo
// also satisfy the delimiter check hence
console.log(bar) // prints: Hello

如你所見,replace 插件並不真正解析你的程式碼,而只是進行簡單的文字替換,這與你的 IDE/編輯器的搜尋與替換功能沒有太大不同。你覺得下面會說什麼?

console.log('foo')
// Guess what?
// ...
// ...
// printed: {"bar":"Hello"}
// as if it were
console.log('{"bar":"Hello"}')

總而言之,你的權宜之計可能是

  • foo['bar'],
  • const { bar }=foo,
  • 避免替換物件,並使用像 __FOO_BAR__, __FOO_BAZ__, ... 這樣的鍵
  • 傳遞 delimiters: ['\b', '\b'] 以允許鍵後跟隨點。

(然而在撰寫本文時,由於有一個待合併的錯誤修復,最後一個似乎還不能使用)。
https://github.com/rollup/plugins/pull/1088

如果你使用 delimiters: ['',''],之前的警告就需要更加謹慎。即使是一個字串字面量 'food' 或 HTML 模板標籤 <footer> 也可能被改成像 '{"bar":"Hello"}d' 或 <{"bar":"Hello"}ter> 這樣的亂碼。因此請明智地命名你的鍵,或根據使用情況使用一些不尋常的分隔符,就像舊版插件曾示範的那樣:delimiters: ['<@','@>']。
https://github.com/rollup/rollup-plugin-replace

然而,由於這種類型的預處理相當基本,在添加替換鍵和使用它們時總是需要小心。