🎩 直接從程式碼區塊建立 CodeSandbox

在 Github 上檢視

remark-codesandbox

🎩 一個 remark 外掛程式,可以直接從程式碼區塊建立 CodeSandbox

npm version

在 CodeSandbox 上線上試用!(沒錯,我們正在 CodeSandbox 內示範 CodeSandbox,何樂而不為!?)

Edit remark-codesandbox demo

特色

  • 🔗 直接從程式碼區塊建立 CodeSandbox 網址
  • ✨ 支援 3 種不同的模式metaiframebutton
  • 🚀 無需建立額外的資料夾或 package.json 檔案
  • 🎉 支援 MDXGatsbyStorybook 文件docz 等...
  • 📦 支援攜帶您自己的自訂範本,甚至直接從同一個儲存庫!
  • ⚡ 一行設定,高度可自訂
  • 💪 非常適合程式庫作者直接從文件中示範用法!

範例

安裝

yarn add -D remark-codesandbox

開始使用

remark-codesandbox 匯入您的 remark 外掛程式。

const codesandbox = require('remark-codesandbox');

remark

remark().use(codesandbox, { mode: 'button' });

MDX

mdx(mdxCode, {
  remarkPlugins: [[codesandbox, { mode: 'button' }]],
});

Gatsby (gatsby-plugin-mdx)

使用 /gatsby 端點來使用 Gatsby 版本的外掛程式。

module.exports = {
  plugins: [
    {
      resolve: 'gatsby-plugin-mdx',
      options: {
        gatsbyRemarkPlugins: [
          {
            resolve: 'remark-codesandbox/gatsby',
            options: {
              mode: 'button',
            },
          },
        ],
      },
    },
  ],
};

Gatsby (gatsby-transformer-remark)

使用 /gatsby 端點來使用 Gatsby 版本的外掛程式。

module.exports = {
  plugins: [
    {
      resolve: 'gatsby-transformer-remark',
      options: {
        plugins: [
          {
            resolve: 'remark-codesandbox/gatsby',
            options: {
              mode: 'button',
            },
          },
        ],
      },
    },
  ],
};

Storybook 文件

config.module.rules.push({
  test: /\.(stories|story)\.mdx$/,
  use: [
    {
      loader: '@mdx-js/loader',
      options: {
        compilers: [createCompiler({})],
        remarkPlugins: [[codesandbox, { mode: 'button' }]],
      },
    },
  ],
});

使用方式

在您的程式碼區塊中新增一個特殊的meta 標籤

```js codesandbox=react
import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
  <h1>Hello remark-codesandbox!</h1>,
  document.getElementById('root')
);
```

然後...就這樣!

以上範例將 mode 設定為 button,會在程式碼區塊後附加一個 CodeSandbox 按鈕。點擊它將會開啟產生的沙箱。是不是很酷!

還有其他模式和額外的設定,請參閱下方的文件以取得更多資訊。

文件

Markdown 語法

在程式碼區塊附加 codesandbox meta 來啟用 remark-codesandbox。這裡的值是沙箱的 id

```js codesandbox=new
// ...
```

有一組預設的官方沙箱範本,您可以在這裡找到清單。一些範例是 new(react)vanilla(parcel)vuestatic...

程式碼區塊的內容將完全取代進入檔案。因此對於 new 範本,內容將完全取代 src/index.js 檔案。請務必匯入範本運作所需的必要套件。

外掛程式也提供一些預設的別名reactnew 的別名。react-component 也是 new 的別名,但將進入點變更為 src/App.js。這樣您就可以在程式碼區塊中匯出 React 元件。

```js codesandbox=react-component
import React from 'react';

export default function App() {
  return <h1>Hello remark-codesandbox!</h1>;
}
```

也可以使用任何現有的沙箱。只需從網址取得沙箱的 idid 通常是沙箱網址的最後 ~5 個隨機字元。也支援從 Github 匯入的沙箱,id 通常是沙箱預覽網址的子網域(~10 個隨機字元)。

```js codesandbox=mqpp1d4r0
// ...
```

想要使用自訂範本並在同一個儲存庫中進行版本控制嗎?使用 file: 結構描述從檔案系統直接載入範本!以下程式碼將從相對於 Markdown 檔案的路徑 ./templates/vanilla-console 載入範本。檔案範本是目錄,其中至少包含一個 package.json 檔案。

與其他範例相同,程式碼區塊的內容將取代範本中的進入檔案。

```js codesandbox=file:./templates/vanilla-console
console.log('this code will replace the entry file content');
```

路徑太長,每次都要輸入嗎?考慮將其建立為自訂範本。這也是建議的方式!

小提示:您可以直接在 codesandbox.io/s 上建立檔案範本,然後在功能表列中選擇 File -> Export to ZIP 來下載它們。將其解壓縮到某個地方... 然後!您就有了一個檔案範本!

查詢參數

也可以透過附加查詢參數來自訂網址。只需將它們附加在沙箱 id 之後。所有選項都是允許的。

```js codesandbox=new?codemirror=1&fontsize=12
// ...
```

您可以內嵌設定幾個特殊的查詢參數。以下所有特殊的查詢參數都不會傳遞到產生的 CodeSandbox 網址,因為它們不受官方支援。

entry

引入一個特殊的查詢參數 entry,可讓您使用程式碼區塊的內容覆寫特定檔案。

```js codesandbox=new?entry=src/App.js
// Override `src/App.js` rather than the default `src/index.js` with this contents of the code block
```

overrideEntry

預設情況下,程式碼區塊中的內容將覆寫進入檔案中的所有內容。您可以透過設定特殊的查詢參數 overrideEntry 來變更此行為。

overrideEntry 設定為一系列行號,以指定您要讓程式碼區塊覆寫進入檔案的哪一部分。以下範例將使用程式碼區塊中的內容取代 react 範本 (src/index.js) 的第 4 行到第 12 行。

```js codesandbox=react?overrideEntry=4-12
ReactDOM.render(
  <h1>Hello remark-codesandbox!</h1>,
  document.getElementById('root')
);
```

有了這個提示,您可以避免將不相關的程式碼傳遞到程式碼區塊,以便讀者可以專注於真正重要的內容。

有一個方便的捷徑,可以僅指定起始行,而無需指定結束行,以從特定的行號開始取代整個進入檔案,而無需知道它的長度。

```js codesandbox=react?overrideEntry=4-
ReactDOM.render(
  <h1>Hello remark-codesandbox!</h1>,
  document.getElementById('root')
);
```

如果您想要按原樣使用範本,而不使用程式碼區塊的任何內容,請新增 ?overrideEntry=false 查詢字串

```js codesandbox=file:./templates/vanilla-console?overrideEntry=false
// This code will not be added to the sandbox
```

style

您也可以覆寫 iframe 模式中使用的預設樣式。

```js codesandbox=react?style=height:1000px
// The generated iframe will have height of 1000px instead of the default 500px
```

您可以傳入以 ; 分隔的多個樣式。所有樣式都將合併並覆寫預設樣式 (width:100%; height:500px; border:0; border-radius:4px; overflow:hidden;)。

```js codesandbox=react?style=height:1000px;width:600px;
// The result style will be: "width:600px; height:1000px; border:0; border-radius:4px; overflow:hidden;"
```

選項

外掛程式接受一組具有以下預設值的選項

{
  remarkPlugins: [
    codesandbox,
    {
      // Can be one of `meta`, `iframe`, or `button`
      mode: 'meta',
      // The query here will be appended to the generated url for every sandbox. Can be `string`, `object`, `URLSearchParams` instance, or `undefined`
      query:
        mode === 'iframe'
          ? {
              fontsize: '14px',
              hidenavigation: 1,
              theme: 'dark',
            }
          : undefined,
      // Define custom templates or override existing ones
      customTemplates: {},
      // Whether to automatically deploy code blocks via CodeSandbox API
      autoDeploy: false,
    },
  ];
}

mode

  • meta:產生 CodeSandbox 網址並將其儲存在 AST 中。此模式本身不會對 Markdown 產生任何視覺上的變更,它對於其他外掛程式或使用者來說很有用,可以啟動並使用沙箱網址執行任何他們想做的事情。該網址將儲存在 node.data.codesandboxUrlnode.data.hProperties.dataCodesandboxUrl 中。一個使用範例是在 UI 中自訂 CodeSandbox 按鈕。

  • iframe:此模式將以產生的沙箱 iframe 標籤完全取代程式碼區塊。iframe 帶有一些預設的查詢參數,但您可以透過 iframeQuery 覆寫它們。

  • button:此模式將保持程式碼區塊不變,並在程式碼區塊之後立即附加一個CodeSandbox 按鈕,如下所示。

    Edit React

query

預設情況下,除了附加到產生的網址的 module 金鑰之外,不會有任何查詢。您可以在這裡自訂每個網址中的查詢。但是,當 modeiframe 時,會有一組預先定義的自訂查詢如下所示。

query =
  mode === 'iframe'
    ? {
        fontsize: '14px',
        hidenavigation: 1,
        theme: 'dark',
      }
    : undefined;

您可以透過將 query 傳遞到選項來覆寫它們。請注意,傳遞的物件將取代預設物件,如果您想要保留它們,請務必再次包含預設查詢。

customTemplates

定義要在程式碼區塊中使用的自訂範本。預期一個物件,其中金鑰為範本 ID,值為範本資訊。

範本資訊是一個物件,具有以下介面。

interface TemplateInfo {
  extends: string;
  entry?: string;
  query?: string | { [key: string]: string } | URLSearchParams;
  files?: { [filePath: string]: { content: string | Object } };
}
  • extends:為了讓定義自訂範本更容易,外掛程式接受一個 extends 金鑰,讓您可以擴充任何現有的範本。該值可以是任何 CodeSandbox id,或 file: 路徑,或任何其他自訂範本 id。如果使用 file: 路徑,建議使用絕對路徑。預設情況下,相對路徑相對於 process.cwd(),這與在程式碼區塊中定義內嵌的相對路徑相反。
  • entry:要顯示在範本中的進入檔案,這也是程式碼區塊將要取代的檔案。允許使用者使用相同的範本/沙箱,但使用不同的檔案來覆寫。
  • query:要附加到產生的網址的查詢參數。它將合併並覆寫上面的options.query 中的金鑰。但是,它將由在程式碼區塊 meta 中內嵌定義的查詢合併和覆寫。
  • files:要合併和覆寫現有檔案的其他檔案。簽名遵循官方 API。建議盡可能在 extends 欄位中使用 file: 路徑,因為它更容易管理和版本控制。

以下是預設的自訂範本。

{
  // Alias `react` to `new`
  react: {
    extends: 'new',
  },
  // Alias `react-component` to `new`, but also override `entry` to `src/App.js`
  'react-component': {
    extends: 'new',
    entry: 'src/App.js',
  },
}

autoDeploy

預設情況下,網址是在本地產生的,而無需呼叫官方 API。API 僅在使用者點擊按鈕或檢視 iframe 時才會被呼叫。這是透過手動在本地建構 parameters,然後透過 lz-string 壓縮它們來完成的。請注意,有一個一般準則,將網址保持在 2000 個字元以下,較長的網址可能在某些瀏覽器中無法運作。

您可以透過將 true 傳遞給 autoDeploy 來繞過此限制。會產生一個網址較短,且網址中具有唯一的 codesandbox_id 的網址。缺點是產生網址需要較長的時間。

一種常見的做法是僅在生產環境中將其設定為 true(或當產生的網址對於您支援的瀏覽器來說太長時),而在開發時將其保持為 false 以加快重新載入時間。

{
  autoDeploy: process.env.NODE_ENV === 'production';
}

貢獻

執行 git clonecd

yarn # Install dependencies

yarn test # Run tests

yarn example # Run build on all examples

yarn bump [patch|minor|major] # Bump version of remark-codesandbox

yarn release # Publish remark-codesandbox to npm

授權

MIT