Quando stiamo sviluppando una WebPart con lo SharePoint Framework (SPFx) può tornare utile sapere se l'applicazione sta girando in Locale, sullo SharePoint con Modern interface oppure sullo SharePoint con la Classic interface.

Sapere se siamo in Locale può tornare utile durante la fase di debug per fornire all'applicazione dei dati di prova.
In Locale significa che l'applicazione sta girando in localhost all'interno della pagina Workbench (normalment https://localhost:4321/temp/workbench.html )

La prima cosa da fare è importare la classe Environment e l'enumerazione EnvironmentType:
TypeScript
import { Environment, EnvironmentType } from '@microsoft/sp-core-library';
l'enumerazioni ha 4 valori che identificano gli ambienti (Enviroment):
TypeScript
export declare enum EnvironmentType {
    /**
     * Indicates that the SharePoint Framework is running inside a test harness, e.g. a unit test.
     * There may be no user interaction at all, and network access in general may be disabled.
     */
    Test = 0,
    /**
     * Indicates that the SharePoint Framework is running on a page from a "localhost" web server,
     * for example the SharePoint Workbench when hosted via "gulp serve".  SharePoint REST API calls
     * will not be available, and in general network access may not authenticate properly.
     * Certain page context information may be using mock values for testing.
     */
    Local = 1,
    /**
     * Indicates that the SharePoint Framework is running on a modern SharePoint web page,
     * with full framework functionality.  This is the normal usage scenario.
     */
    SharePoint = 2,
    /**
     * Indicates that the framework was hosted by a classic server-rendered SharePoint page.
     * Some functionality may be limited, e.g. various extensibility APIs may not be supported.
     */
    ClassicSharePoint = 3,
}
controllando la proprietà Environment.type è possibile sapere se siamo in Locale:
TypeScript
if ( Environment.type === EnvironmentType.Local) {
  // carica da locale i dati di prova (Mock)
} else {
  // carica da remoto i dati reali
}
Potrebbe interessarti anche: