refactor(ganalytics, gtag): move options out of themeConfig (#5832)

* refactor(ganalytics, gtag): move options out of themeConfig

* Forbid themeConfig options

* Add PR link

* Add key names to error message

* Fix?

* Doc updates

Co-authored-by: Sébastien Lorber <slorber@users.noreply.github.com>
This commit is contained in:
Joshua Chen 2021-11-10 19:04:43 +08:00 committed by GitHub
parent f5732e7589
commit ac88d979f1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
14 changed files with 274 additions and 106 deletions

View file

@ -6,30 +6,23 @@
*/
import path from 'path';
import type {LoadContext, Plugin, HtmlTags} from '@docusaurus/types';
import type {ThemeConfig} from '@docusaurus/plugin-google-analytics';
export default function pluginGoogleAnalytics(context: LoadContext): Plugin {
const {
siteConfig: {themeConfig},
} = context;
const {googleAnalytics} = themeConfig as ThemeConfig;
if (!googleAnalytics) {
throw new Error(
`You need to specify "googleAnalytics" object in "themeConfig" with "trackingId" field in it to use docusaurus-plugin-google-analytics.`,
);
}
const {trackingID, anonymizeIP} = googleAnalytics;
if (!trackingID) {
throw new Error(
'You specified the "googleAnalytics" object in "themeConfig" but the "trackingID" field was missing. ' +
'Please ensure this is not a mistake.',
);
}
import {Joi} from '@docusaurus/utils-validation';
import type {
LoadContext,
Plugin,
HtmlTags,
OptionValidationContext,
ValidationResult,
ThemeConfig,
ThemeConfigValidationContext,
} from '@docusaurus/types';
import type {PluginOptions} from '@docusaurus/plugin-google-analytics';
export default function pluginGoogleAnalytics(
context: LoadContext,
options: PluginOptions,
): Plugin {
const {trackingID, anonymizeIP} = options;
const isProd = process.env.NODE_ENV === 'production';
return {
@ -74,3 +67,26 @@ export default function pluginGoogleAnalytics(context: LoadContext): Plugin {
},
};
}
const pluginOptionsSchema = Joi.object<PluginOptions>({
trackingID: Joi.string().required(),
anonymizeIP: Joi.boolean().default(false),
});
export function validateOptions({
validate,
options,
}: OptionValidationContext<PluginOptions>): ValidationResult<PluginOptions> {
return validate(pluginOptionsSchema, options);
}
export function validateThemeConfig({
themeConfig,
}: ThemeConfigValidationContext<ThemeConfig>): ValidationResult<ThemeConfig> {
if (themeConfig.googleAnalytics) {
throw new Error(
'The "googleAnalytics" field in themeConfig should now be specified as option for plugin-google-analytics. More information at https://github.com/facebook/docusaurus/pull/5832.',
);
}
return themeConfig;
}

View file

@ -5,9 +5,9 @@
* LICENSE file in the root directory of this source tree.
*/
export interface ThemeConfig {
googleAnalytics?: {
trackingID: string;
anonymizeIP?: boolean;
};
}
export type PluginOptions = {
trackingID: string;
anonymizeIP: boolean;
};
export type Options = Partial<PluginOptions>;