microsoft / vscode

Visual Studio Code
https://code.visualstudio.com
MIT License
162.59k stars 28.66k forks source link

Improve localization experience of WebViews #206547

Open ykawakamy opened 6 months ago

ykawakamy commented 6 months ago

I progress to develoment webview-panel using react. (see. https://github.com/microsoft/vscode-webview-ui-toolkit-samples/tree/main/frameworks/hello-world-react-vite )

Couldn't work l10n.t() in react app. I think that don't load l10n/bundle.l10n.xx.json.

Can I initialize l10n in react app with the same locale as extension?

-- sorry, i'm not good at English.

ykawakamy commented 6 months ago

solved it myself.

my solution.

    // in Webview on my extension
    const bundleUrl = webview.asWebviewUri(vscode.l10n.uri!);

    return /*html*/ `<!DOCTYPE html>
      <html lang="en">
      <head>
        <meta charset="UTF-8">

        <!-- // connect-src important -->
        <meta http-equiv="Content-Security-Policy" 
          content="default-src 'none'; style-src ${webview.cspSource}; font-src ${webview.cspSource}; script-src 'nonce-${nonce}'; connect-src ${webview.cspSource};">
      </head>
      <body>
        <div id="root"></div>
        <!-- // pass bundleUri to scriptUri module.  -->
        <script nonce="${nonce}">
          const bundleUri="${bundleUrl}";
        </script>
        <script nonce="${nonce}" src="${scriptUri}"></script>
      </body>
      </html>`;
  }
// in scriptUri module(typescript)
import { createRoot } from "react-dom/client";
import * as  l10n from "@vscode/l10n";

declare const bundleUri: string;

export async function l10nInitalize(){
  await l10n.config({uri:bundleUri});
}

const container = document.getElementById('root')!;
const root = createRoot(container);
l10nInitalize().then(()=>{
  root.render(<App/>);
}, 
(e)=>{ console.error(e);}
);

Please let me know if there is another better way.

TylerLeonhardt commented 6 months ago

Yeah this is the best solution for this at the moment. Ideally this is loaded for you automatically.

This is related to https://github.com/microsoft/vscode/issues/170919 which uses WebViews.