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: add helmet plugin #180

Merged
merged 23 commits into from
May 19, 2020
Merged
Show file tree
Hide file tree
Changes from 5 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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-test-renderer": "^16.9.0",
"umi": "^3.1.0",
"umi": "^3.2.0-beta.2",
"yorkie": "^2.0.0"
},
"gitHooks": {
Expand Down
19 changes: 19 additions & 0 deletions packages/plugin-helmet/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# @umijs/plugin-helmet

> @umijs/plugin-ssr-helmet.

See our website [@umijs/plugin-helmet](https://umijs.org/plugins/plugin-helmet) for more information.

## Install

Using npm:

```bash
$ npm install --save-dev @umijs/plugin-helmet
```

or using yarn:

```bash
$ yarn add @umijs/plugin-helmet --dev
```
13 changes: 13 additions & 0 deletions packages/plugin-helmet/fixtures/normal/.umirc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@

export default {
history: {
type: 'memory',
options: {
initialEntries: ['/'],
},
},
mountElementId: '',
routes: [
{ path: '/', component: 'index' },
],
}
Empty file.
13 changes: 13 additions & 0 deletions packages/plugin-helmet/fixtures/normal/src/pages/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import React from 'react';
import { Helmet } from '../.umi-test/core/umiExports';

export default function() {
return (
<div>
<h1>Hello Helmet</h1>
<Helmet>
<title>Title Helmet</title>
</Helmet>
</div>
);
}
14 changes: 14 additions & 0 deletions packages/plugin-helmet/fixtures/ssr/.umirc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@

export default {
ssr: {},
history: {
type: 'memory',
options: {
initialEntries: ['/'],
},
},
mountElementId: '',
routes: [
{ path: '/', component: 'index' },
],
}
Empty file.
14 changes: 14 additions & 0 deletions packages/plugin-helmet/fixtures/ssr/src/pages/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import React from 'react';
import { Helmet } from '../.umi-test/core/umiExports';

export default function() {
return (
<div>
<h1>Hello Helmet</h1>
<Helmet>
<html lang="zh" data-direction="top" />
<title>Title Helmet</title>
</Helmet>
</div>
);
}
35 changes: 35 additions & 0 deletions packages/plugin-helmet/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"name": "@umijs/plugin-helmet",
"version": "1.0.0-beta.1",
"description": "@umijs/plugin-helmet",
"main": "lib/index.js",
"types": "lib/index.d.ts",
"files": [
"lib",
"src"
],
"repository": {
"type": "git",
"url": "https://github.com/umijs/plugins"
},
"keywords": [
"umi"
],
"authors": [
"chencheng <sorrycc@gmail.com> (https://github.com/sorrycc)"
ycjcl868 marked this conversation as resolved.
Show resolved Hide resolved
],
"license": "MIT",
"bugs": "http://github.com/umijs/plugins/issues",
"homepage": "https://github.com/umijs/plugins/tree/master/packages/plugin-helmet#readme",
"peerDependencies": {
"umi": "3.x"
},
"publishConfig": {
"access": "public"
},
"dependencies": {
"cheerio": "^1.0.0-rc.3",
ycjcl868 marked this conversation as resolved.
Show resolved Hide resolved
"@types/react-helmet-async": "^1.0.3",
"react-helmet-async": "^1.0.5"
}
}
92 changes: 92 additions & 0 deletions packages/plugin-helmet/src/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { join } from 'path';
import { existsSync } from 'fs';
import { Service } from 'umi';
import { render, waitForDomChange, cleanup } from '@testing-library/react';

const fixtures = join(__dirname, '..', 'fixtures');

afterEach(() => {
cleanup();
});

test('normal', async () => {
const cwd = join(fixtures, 'normal');
const service = new Service({
cwd,
plugins: [require.resolve('./')],
});
await service.run({
name: 'g',
args: {
_: ['g', 'tmp'],
},
});

const reactNode = require(join(cwd, 'src', '.umi-test', 'umi.ts')).default;
const { container } = render(reactNode);

expect(container.querySelector('h1').textContent).toEqual('Hello Helmet');
await waitForDomChange();
expect(document.title).toEqual('Title Helmet');
});

const htmlTemplate = `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"
/>
<link rel="stylesheet" href="/umi.css" />
<script>
window.routerBase = "/";
</script>
<script>
//! umi version: undefined
</script>
</head>
<body>
<div id="root"></div>

<script src="/umi.js"></script>
</body>
</html>`;

test('ssr', async () => {
const cwd = join(fixtures, 'ssr');
const tmpServerFile = join(cwd, 'src', '.umi-test', 'core', 'server.ts');

delete require.cache[tmpServerFile];
const service = new Service({
cwd,
plugins: [require.resolve('./')],
});
await service.run({
name: 'g',
args: {
_: ['g', 'tmp'],
},
});

const { HelmetProvider } = require(join(
cwd,
'src',
'.umi-test',
'core',
'umiExports.ts',
));
// must set false, because of jest env patch the document
HelmetProvider.canUseDOM = false;

expect(existsSync(tmpServerFile)).toBeTruthy();
const serverRender = require(tmpServerFile).default;
const { html } = await serverRender({
path: '/',
htmlTemplate,
mountElementId: 'root',
});

expect(html).toMatch(/<title data-rh=\"true\">Title Helmet<\/title>/);
expect(html).toMatch(/<html lang=\"zh\" data-direction=\"top\">/);
});
35 changes: 35 additions & 0 deletions packages/plugin-helmet/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { readFileSync } from 'fs';
import { join, dirname } from 'path';

import { IApi, utils } from 'umi';

const { winPath, Mustache } = utils;

export default (api: IApi) => {
const helmetPkgPath = winPath(
dirname(require.resolve('react-helmet-async/package')),
);
api.onGenerateFiles(async () => {
const runtimeTpl = join(winPath(__dirname), 'templates', 'runtime.tpl');
ycjcl868 marked this conversation as resolved.
Show resolved Hide resolved
const runtimeContent = readFileSync(runtimeTpl, 'utf-8');
api.writeTmpFile({
path: 'plugin-helmet/runtime.ts',
content: Mustache.render(runtimeContent, {
HelmetPkg: helmetPkgPath,
SSR: !!api.config.ssr,
Utils: winPath(require.resolve('./utils')),
ycjcl868 marked this conversation as resolved.
Show resolved Hide resolved
}),
});
});

api.addRuntimePlugin(() =>
winPath(join(api.paths!.absTmpPath, 'plugin-helmet', 'runtime.ts')),
);

api.addUmiExports(() => [
{
exportAll: true,
source: helmetPkgPath,
},
]);
};
18 changes: 18 additions & 0 deletions packages/plugin-helmet/src/templates/runtime.tpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import React from 'react';
import { HelmetProvider } from '{{{ HelmetPkg }}}';

// helmetContext for ssr
const helmetContext = {};

{{#SSR}}
const { modifyHTMLHOC } = require('{{{ Utils }}}');
export const ssr = {
modifyHTML: modifyHTMLHOC({
helmetContext,
}),
};
{{/SSR}}

export function rootContainer(container) {
return React.createElement(HelmetProvider, { context: helmetContext }, container);
};
31 changes: 31 additions & 0 deletions packages/plugin-helmet/src/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
export const modifyHTMLHOC = ({ helmetContext }) => html => {
const { Stream } = require('stream');
const cheerio = require('cheerio');
const helmet = helmetContext.helmet;
if (!helmet) return html;
const title = helmet.title.toString();
const htmlAttributes = helmet.htmlAttributes.toComponent();
const meta = helmet.meta.toString();
const link = helmet.link.toString();
if (html instanceof Stream) {
// TODO
return html;
}
const $ = cheerio.load(html);
// keep latest
if (title) {
$('head').prepend(title);
}
if (meta) {
$('head').append(meta);
}
if (link) {
$('link').append(link);
}
if (Object.keys(htmlAttributes)) {
Object.keys(htmlAttributes).forEach(attrKey => {
$('html').attr(attrKey, htmlAttributes[attrKey]);
});
}
return $.html();
};
7 changes: 5 additions & 2 deletions packages/plugin-locale/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,17 @@ const setupTests = () => {
if (global.Intl) {
Intl.NumberFormat = IntlPolyfill.NumberFormat;
Intl.DateTimeFormat = IntlPolyfill.DateTimeFormat;
// https://github.com/andyearnshaw/Intl.js/issues/256#issuecomment-267705446
// https://github.com/andyearnshaw/Intl.js#regexp-cache--restore
IntlPolyfill.__disableRegExpRestore();
} else {
global.Intl = IntlPolyfill;
}
};

const fixtures = join(__dirname, '..', 'fixtures');

beforeEach(() => {
beforeAll(() => {
setupTests();
});

Expand All @@ -42,7 +45,7 @@ test('normal', async () => {
});

const reactNode = require(join(cwd, 'src', '.umi-test', 'umi.ts')).default;
const { container, getByText, rerender } = render(reactNode);
const { container, getByText } = render(reactNode);

fireEvent.click(getByText('en-US'));
expect(container.querySelector('h2')?.textContent).toEqual('Hello Traveler');
Expand Down
Loading