Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(v2): injectHtmlTags API to inject head and/or body html tags #2057

Merged
merged 11 commits into from
Nov 30, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,18 +34,18 @@
"@types/loader-utils": "^1.1.3",
"@types/lodash": "^4.14.149",
"@types/lodash.kebabcase": "^4.1.6",
"@types/node": "^12.12.11",
"@types/node": "^12.12.14",
"@types/react": "^16.9.13",
"@types/react-dev-utils": "^9.0.1",
"@types/semver": "^6.2.0",
"@types/shelljs": "^0.8.6",
"@types/webpack": "^4.41.0",
"@types/webpack-dev-server": "^3.4.0",
"@types/webpack-dev-server": "^3.9.0",
"@types/webpack-merge": "^4.1.5",
"babel-eslint": "^10.0.3",
"enzyme": "^3.10.0",
"enzyme-adapter-react-16": "^1.15.1",
"eslint": "^6.7.0",
"eslint": "^6.7.1",
"eslint-config-airbnb": "^18.0.1",
"eslint-config-prettier": "^6.7.0",
"eslint-plugin-header": "^3.0.0",
Expand All @@ -57,7 +57,7 @@
"jest": "^24.9.0",
"lerna": "^3.19.0",
"lerna-changelog": "^0.8.3",
"lint-staged": "^9.4.3",
"lint-staged": "^9.5.0",
"prettier": "^1.19.1",
"react": "^16.8.4",
"react-dom": "^16.8.4",
Expand Down
2 changes: 1 addition & 1 deletion packages/docusaurus-plugin-content-docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"dependencies": {
"@docusaurus/mdx-loader": "^2.0.0-alpha.36",
"@docusaurus/utils": "^2.0.0-alpha.36",
"execa": "^3.3.0",
"execa": "^3.4.0",
"fs-extra": "^8.1.0",
"globby": "^10.0.1",
"import-fresh": "^3.2.1",
Expand Down
33 changes: 32 additions & 1 deletion packages/docusaurus-types/src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,15 @@ export interface LoadContext {
baseUrl: string;
}

export interface Props extends LoadContext {
export interface InjectedHtmlTags {
headTags: string;
preBodyTags: string;
postBodyTags: string;
}

export type HtmlTags = string | HtmlTagObject | (string | HtmlTagObject)[];

export interface Props extends LoadContext, InjectedHtmlTags {
routesPaths: string[];
plugins: Plugin<any>[];
}
Expand Down Expand Up @@ -104,6 +112,11 @@ export interface Plugin<T> {
getPathsToWatch?(): string[];
getClientModules?(): string[];
extendCli?(cli: Command): void;
injectHtmlTags?(): {
headTags?: HtmlTags;
preBodyTags?: HtmlTags;
postBodyTags?: HtmlTags;
};
}

export type PluginConfig = [string, Object] | [string] | string;
Expand Down Expand Up @@ -152,3 +165,21 @@ export interface ConfigureWebpackUtils {
getCacheLoader: (isServer: boolean, cacheOptions?: {}) => Loader | null;
getBabelLoader: (isServer: boolean, babelOptions?: {}) => Loader;
}

interface HtmlTagObject {
/**
* Attributes of the html tag
* E.g. `{'disabled': true, 'value': 'demo', 'rel': 'preconnect'}`
*/
attributes?: {
[attributeName: string]: string | boolean;
};
/**
* The tag name e.g. `div`, `script`, `link`, `meta`
*/
tagName: string;
/**
* The inner HTML
*/
innerHTML?: string;
}
3 changes: 2 additions & 1 deletion packages/docusaurus/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
"express": "^4.17.1",
"fs-extra": "^8.1.0",
"globby": "^10.0.1",
"html-tags": "^3.1.0",
"html-webpack-plugin": "^4.0.0-beta.11",
"import-fresh": "^3.2.1",
"lodash": "^4.17.15",
Expand All @@ -75,7 +76,7 @@
"semver": "^6.3.0",
"shelljs": "^0.8.3",
"std-env": "^2.2.1",
"style-loader": "^1.0.0",
"style-loader": "^1.0.1",
"terser-webpack-plugin": "^2.2.1",
"wait-file": "^1.0.5",
"webpack": "^4.41.2",
Expand Down
5 changes: 4 additions & 1 deletion packages/docusaurus/src/client/serverEntry.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import ssrTemplate from './templates/ssr.html.template';

// Renderer for static-site-generator-webpack-plugin (async rendering via promises)
export default async function render(locals) {
const {routesLocation} = locals;
const {routesLocation, headTags, preBodyTags, postBodyTags} = locals;
const location = routesLocation[locals.path];
await preload(routes, location);
const modules = new Set();
Expand Down Expand Up @@ -76,6 +76,9 @@ export default async function render(locals) {
chunkManifestScript,
htmlAttributes: htmlAttributes || '',
bodyAttributes: bodyAttributes || '',
headTags,
preBodyTags,
postBodyTags,
metaAttributes,
scripts,
stylesheets,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,13 @@
<meta name="viewport" content="width=device-width">
<meta name="generator" content="Docusaurus">
<title><%= htmlWebpackPlugin.options.title %></title>
<%= htmlWebpackPlugin.options.headTags %>
<%= htmlWebpackPlugin.tags.headTags %>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this leftover by mistake?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no its not. So html webpack plugin by default will inject the required script at postbody. So since we want to add our own postbody tags, we have to set “inject:false” to htmlwebpackplugin and then put the injection place. See https://github.com/jantimon/html-webpack-plugin/tree/master/examples/custom-insertion-position

Copy link
Contributor Author

@endiliey endiliey Nov 30, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

*at posthead and postbody.

</head>
<body>
<%= htmlWebpackPlugin.options.preBodyTags %>
<div id="__docusaurus"></div>
<%= htmlWebpackPlugin.tags.bodyTags %>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This too.

<%= htmlWebpackPlugin.options.postBodyTags %>
</body>
</html>
3 changes: 3 additions & 0 deletions packages/docusaurus/src/client/templates/ssr.html.template.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ module.exports = `
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="generator" content="Docusaurus">
<%- headTags %>
endiliey marked this conversation as resolved.
Show resolved Hide resolved
<%- chunkManifestScript %>
<% metaAttributes.forEach((metaAttribute) => { %>
<%- metaAttribute %>
Expand All @@ -21,12 +22,14 @@ module.exports = `
<% }); %>
</head>
<body <%- bodyAttributes %>>
<%- preBodyTags %>
<div id="__docusaurus">
<%- appHtml %>
</div>
<% scripts.forEach((script) => { %>
<script type="text/javascript" src="<%= baseUrl %><%= script %>"></script>
<% }); %>
<%- postBodyTags %>
</body>
</html>
`;
7 changes: 6 additions & 1 deletion packages/docusaurus/src/commands/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export async function start(
const protocol: string = process.env.HTTPS === 'true' ? 'https' : 'http';
const port: number = await getPort(cliOptions.port);
const host: string = getHost(cliOptions.host);
const {baseUrl} = props;
const {baseUrl, headTags, preBodyTags, postBodyTags} = props;
const urls = prepareUrls(protocol, host, port);
const openUrl = normalizeUrl([urls.localUrlForBrowser, baseUrl]);

Expand All @@ -90,8 +90,13 @@ export async function start(
__dirname,
'../client/templates/index.html.template.ejs',
),
// so we can define the position where the scripts are injected
inject: false,
filename: 'index.html',
title: siteConfig.title,
headTags,
preBodyTags,
postBodyTags,
}),
// This is necessary to emit hot updates for webpack-dev-server
new HotModuleReplacementPlugin(),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

module.exports = function() {
return {
name: 'plugin-empty',
};
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

module.exports = function() {
return {
name: 'plugin-headTags-only',
injectHtmlTags() {
return {
headTags: [
{
tagName: 'link',
attributes: {
rel: 'preconnect',
href: 'www.google-analytics.com',
},
},
`<meta name="generator" content="docusaurus">`,
],
};
},
};
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

module.exports = function() {
return {
name: 'plugin-postBody-tags',
injectHtmlTags() {
return {
postBodyTags: [
{
tagName: 'div',
innerHTML: 'Test content',
},
],
};
},
};
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

module.exports = function() {
return {
name: 'plugin-preBodyTags',
injectHtmlTags() {
return {
preBodyTags: {
tagName: 'script',
attributes: {
type: 'text/javascript',
},
innerHTML: 'window.foo = null;',
},
};
},
};
};
122 changes: 122 additions & 0 deletions packages/docusaurus/src/server/html-tags/__tests__/htmlTags.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import {htmlTagObjectToString} from '../htmlTags';

describe('htmlTagObjectToString', () => {
test('simple html tag', () => {
expect(
htmlTagObjectToString({
tagName: 'script',
attributes: {
type: 'text/javascript',
src:
'https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.0/clipboard.min.js',
async: true,
},
}),
).toMatchInlineSnapshot(
`"<script type=\\"text/javascript\\" src=\\"https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.0/clipboard.min.js\\" async></script>"`,
);

expect(
htmlTagObjectToString({
tagName: 'link',
attributes: {
rel: 'preconnect',
href: 'www.google-analytics.com',
},
}),
).toMatchInlineSnapshot(
`"<link rel=\\"preconnect\\" href=\\"www.google-analytics.com\\">"`,
);

expect(
htmlTagObjectToString({
tagName: 'div',
attributes: {
style: 'background-color:lightblue',
},
innerHTML: 'Lightblue color here',
}),
).toMatchInlineSnapshot(
`"<div style=\\"background-color:lightblue\\">Lightblue color here</div>"`,
);

expect(
htmlTagObjectToString({
tagName: 'div',
innerHTML: 'Test',
}),
).toMatchInlineSnapshot(`"<div>Test</div>"`);
});

test('valid html void tag', () => {
expect(
htmlTagObjectToString({
tagName: 'meta',
attributes: {
name: 'generator',
content: 'Docusaurus',
},
}),
).toMatchInlineSnapshot(
`"<meta name=\\"generator\\" content=\\"Docusaurus\\">"`,
);

expect(
htmlTagObjectToString({
tagName: 'img',
attributes: {
src: '/img/docusaurus.png',
alt: 'Docusaurus logo',
height: '42',
width: '42',
},
}),
).toMatchInlineSnapshot(
`"<img src=\\"/img/docusaurus.png\\" alt=\\"Docusaurus logo\\" height=\\"42\\" width=\\"42\\">"`,
);
});

test('invalid tag', () => {
expect(() =>
htmlTagObjectToString({
tagName: 'endiliey',
attributes: {
this: 'is invalid',
},
}),
).toThrowErrorMatchingInlineSnapshot(
`"Error loading {\\"tagName\\":\\"endiliey\\",\\"attributes\\":{\\"this\\":\\"is invalid\\"}}, \\"endiliey\\" is not a valid HTML tags"`,
);
});

test('invalid tagName', () => {
expect(() =>
htmlTagObjectToString({
tagName: true,
}),
).toThrowErrorMatchingInlineSnapshot(
`"{\\"tagName\\":true} is not a valid HTML tag object. \\"tagName\\" must be defined as a string"`,
);
});

test('invalid html tag object', () => {
expect(() =>
htmlTagObjectToString('fooofofoofo'),
).toThrowErrorMatchingInlineSnapshot(
`"\\"fooofofoofo\\" is not a valid HTML tag object"`,
);

expect(() =>
htmlTagObjectToString(null),
).toThrowErrorMatchingInlineSnapshot(
`"\\"null\\" is not a valid HTML tag object"`,
);
});
});
Loading