@gravity-ui/app-layout ! (简体中文)

安装
npm install --save-dev @gravity-ui/app-layout
使用量
与 express数字 :
import express from 'express';
import {createRenderFunction} from '@gravity-ui/app-layout';
const app = express();
const renderLayout = createRenderFunction();
app.get('/', function (req, res) {
res.send(
renderLayout({
// RenderParams
title: 'Home page',
bodyContent: {
root: 'Hello world!',
},
}),
);
});
app.listen(3000);
地点
interface RenderParams<Data, Plugins> {
// Any json compatible data, will be set to window.__DATA__ on the page
data?: Data;
// favicon
icon?: Icon;
// nonce to be set on the appropriate tags
nonce?: string;
// base tag attributes
base?: Base;
// common options
// Page title
title: string;
// language of page, will be set to html tag
lang?: string;
isMobile?: boolean;
// html attributes
htmlAttributes?: string;
// header tag content
// meta tags
meta?: Meta[];
// link tags
links?: Link[];
// script tags
scripts?: Script[];
// style tags
styleSheets?: Stylesheet[];
// script tags with inlined code
inlineScripts?: string[];
// style tags with inlined styles
inlineStyleSheets?: string[];
// content of body tag
bodyContent?: {
// class name for body tag
className?: string;
// body attributes
attributes?: string;
// body content before div tag with id root
beforeRoot?: string;
// innerHtml content of div tag with id root
root?: string;
// body content after div tag with id root
afterRoot?: string;
};
// plugins options
pluginsOptions?: Partial<PluginsOptions<Plugins>>;
}
基础
说明 base 标签 :
interface Base {
href?: string;
target?: HTMLBaseElement['target'];
}
示例
renderLayout({
title: 'Home page',
base: {target: '_top'},
});
将作为:
<base target="_top" />
元数据
说明 meta 标签 :
interface Meta {
name: string;
content: string;
}
示例
const meta = [
{name: 'description', content: 'some text'},
{name: 'robots', content: 'noindex'},
{name: 'og:title', content: 'Some title'},
];
将作为:
<meta name="description" content="some text" />
<meta name="robots" content="noindex" />
<meta property="og:title" content="Some title" />
图标
描述页面外观 :
interface Icon {
type?: string;
sizes?: string;
href?: string;
}
默认值为:
const icon = {
type: 'image/png',
sizes: '16x16',
href: '/favicon.png',
};
链接
说明 link 标签 :
interface Link {
as?: string;
href: string;
rel?: string;
type?: string;
sizes?: string;
title?: HTMLLinkElement['title'];
crossOrigin?: '' | 'anonymous' | 'use-credentials';
}
示例
const link = {
href: 'myFont.woff2',
rel: 'preload',
as: 'font',
type: 'font/woff2',
crossOrigin: 'anonymous',
};
将作为:
<link href="myFont.woff2" rel="preload" as="font" type="font/woff2" crossorigin="anonymous" />
脚本
描述与预装脚本的链接 :
interface Script {
src: string;
defer?: boolean;
async?: boolean;
crossOrigin?: '' | 'anonymous' | 'use-credentials';
type?: 'importmap' | 'module' | string;
}
示例
const script = {
src: 'url/to/script',
defer: true,
async: false,
crossOrigin: 'anonymous',
};
将作为:
<link href="url/to/script" rel="preload" as="script" crossorigin="anonymous" />
<script src="url/to/script" defer="true" async="false" crossorigin="anonymous" nonce="..."></script>
样式表
描述样式的链接 :
interface Stylesheet {
href: string;
}
示例
const styleSheet = {
href: 'url/to/stylesheet',
};
将作为:
<link href="url/to/stylesheet" rel="stylesheet" />
插件
Render功能可以通过插件来扩展. 插件可能会重写定义的用户渲染内容 .
插件是对象 name 财务报告和审定财务报表 apply 属性 :
interface Plugin<Options = any, Name = string> {
name: Name;
apply: (params: {
options: Options | undefined; // passed through `renderLayout` function in `pluginsOptions` parameter.
commonOptions: CommonOptions;
renderContent: RenderContent;
/** @deprecated use `renderContent.helpers` instead */
utils: RenderHelpers;
}) => void;
}
interface CommonOptions {
name: string;
title: string;
lang?: string;
isMobile?: boolean;
}
export interface HeadContent {
base?: Base;
scripts: Script[];
helpers: RenderHelpers;
links: Link[];
meta: Meta[];
styleSheets: Stylesheet[];
inlineStyleSheets: string[];
inlineScripts: string[];
title: string;
}
export interface BodyContent {
attributes: Attributes;
beforeRoot: string[];
root?: string;
afterRoot: string[];
}
export interface RenderContent extends HeadContent {
htmlAttributes: Attributes;
bodyContent: BodyContent;
}
export interface RenderHelpers {
renderScript(script: Script): string;
renderInlineScript(content: string): string;
renderStyle(style: Stylesheet): string;
renderInlineStyle(content: string): string;
renderMeta(meta: Meta): string;
renderLink(link: Link): string;
attrs(obj: Attributes): string;
}
此软件包中有一些插件 :
谷歌分析
在页面上添加google分析计数器.
用法 :
import {createRenderFunction, createGoogleAnalyticsPlugin} from '@gravity-ui/app-layout';
const renderLayout = createRenderFunction([createGoogleAnalyticsPlugin()]);
app.get((req, res) => {
res.send(
renderLayout({
title: 'Home page',
pluginsOptions: {
googleAnalytics: {
useBeaconTransport: true, // enables use of navigator.sendBeacon
counter: {
id: 'some id',
},
},
},
}),
);
});
插件选项 :
interface GoogleAnalyticsCounter {
id: string;
}
interface GoogleAnalyticsOptions {
useBeaconTransport?: boolean;
counter: GoogleAnalyticsCounter;
}
扬德克·梅特里卡
在页面上添加 Yandex 度量衡.
用法 :
import {createRenderFunction, createYandexMetrikaPlugin} from '@gravity-ui/app-layout';
const renderLayout = createRenderFunction([createYandexMetrikaPlugin()]);
app.get((req, res) => {
res.send(
renderLayout({
title: 'Home page',
pluginsOptions: {
yandexMetrika: {
counter: {
id: 123123123,
defer: true,
clickmap: true,
trackLinks: true,
accurateTrackBounce: true,
},
},
},
}),
);
});
插件选项 :
export type UserParams = {
[x: string]: boolean | string | number | null | UserParams;
};
export interface MetrikaCounter {
id: number;
defer: boolean;
clickmap: boolean;
trackLinks: boolean;
accurateTrackBounce: boolean | number;
webvisor?: boolean;
nonce?: string;
encryptedExperiments?: string;
triggerEvent?: boolean;
trackHash?: boolean;
ecommerce?: boolean | string;
type?: number;
userParams?: UserParams;
}
export type MetrikaOptions = {
src?: string;
counter: MetrikaCounter | MetrikaCounter[];
};
版式
从 Webpack 资产列表文件中添加脚本和样式.
用法 :
import {createRenderFunction, createLayoutPlugin} from '@gravity-ui/app-layout';
const renderLayout = createRenderFunction([
createLayoutPlugin({manifest: 'path/to/assets-manifest.json', publicPath: '/build/'}),
]);
app.get((req, res) => {
res.send(
renderLayout({
title: 'Home page',
pluginsOptions: {
layout: {
name: 'home',
},
},
}),
);
});
插件选项 :
export interface LayoutOptions {
name: string;
prefix?: string;
}
公共路径倒计时
从备份地址装入初始脚本和样式表 publicPath 失败.
用法 :
createLayoutPlugin({
manifest: 'path/to/assets-manifest.json',
publicPath: 'https://static.example.com/build/',
publicPathFallbacks: ['https://backup.example.com/build/', '/build/'],
});
这些选项也可在以下表格中找到: createDefaultPlugins({layout: …})启用布局插件 pluginsOptions.layout.name,如上述例子。 选择 publicPathFallbacks 或通过 [] 保存正常渲染.
您也可以使用回调函数 :
createLayoutPlugin({
manifest: 'path/to/assets-manifest.json',
publicPath: 'https://static.example.com/build/',
publicPathFallbacks: () =>
location.hostname.endsWith('.example.org')
? ['https://backup.example.org/build/', '/build/']
: ['/build/'],
});
该功能运行一次,必须自成一体,不得关闭或进口. 它接收 {publicPath};对于根相对主路径,该值包括 layout.prefix返回 [] 使用主地址而不重试.
装入器被捆绑和精密化,当应用放出时. 用户调用从编译的服务器代码中序列化 Function.prototype.toString(): 重建等转型 keepNames 能够注入外部帮助( e)__name)在浏览器中找不到。 在您的终端服务器构建中测试回调 。 HTML 解析期间, 如果靴子拖放, 同步注册将恢复脚本标记通过 document.write,但受浏览器限制;如果CSP屏蔽了注册脚本,恢复也无济于事.
重试选项 :
interface AssetRetryOptions {
retries?: number; // Additional attempts per address. Default: 0.
delayMs?: number; // Delay before the first retry, in milliseconds. Default: 500.
factor?: number; // Multiplier for subsequent retry delays. Default: 2.
maxDelayMs?: number; // Maximum retry delay, in milliseconds. Default: 3000.
timeoutMs?: number; // Attempt timeout, in milliseconds. Default: 10000; 0 disables.
}
通过这些选项为 assetRetry 改为 createLayoutPlugin。默认情况下,一个资源错误在不重试同一 URL的情况下切换到下一个地址。 设定 retries 以指数延迟的方式进行更多的尝试。 加载器记得最后一个成功的地址并在那里开始后续的脚本,将剩下的地址循环作为备份. 样式表总是从 publicPath,然后在配置的顺序中尝试备份地址。 单个失败不会改变首选地址;只有在成功加载后才会改变. 飞行资源保持其候选顺序。 明确 undefined 选项值使用默认值.
每个脚本或样式表尝试都有一个 timeoutMs 限制(默认为1,000毫秒)。 超时跟装入错误一样遵循同样的重试策略:在尝试时重试当前 URL,然后尝试下一个地址. 设定 0 以禁用超时。 加载器会去掉超时出元素并忽略其后回调;去掉一个脚本并不能保证取消其执行.
备份地址必须在同一相对路径上为相同的构建文件服务. 不包括查询参数或基址中的片段. 被添加了倒挂并自动去掉重复地址. 类似路径 /build/ 相对于页面来源; 明确包含任何应用程序前缀。 允许 CSP 中的备份域并配置 CORS .
正在装入行为 :
- 支助
defer没有脚本async或者说type样式表nonce财务报告和审定财务报表crossOrigin其他资源保持正常的渲染。 响应片段的所有管理资产都由靴子后发射的单一内行脚本按头顺序(样式表,然后是脚本)注册;原始脚本标记不渲染出. - 样式表包含在HTML中,并同时加载,即使JavaScript加载器无法启动. 部分样式的内容在重试时可能可见. 脚本在样式表尝试完成后运行, DOM 已准备好 .
DOMContentLoaded并不意味着应用程序已装入完毕. - 最终失败
app-layout:asset-load-error打开window。事件细节包含{type, originalUrl, attempts}并被导出AssetLoadError类型;attempts列出尝试的URL,包括重试。 在装入资源前注册处理器 。 最终样式表加载失败不会阻断脚本; 最终脚本加载失败会阻止加载者的脚本队列 . - 用于流出时的早期脚本, 使用
renderScripts(content, scripts, state),则renderHeadContent(content, state)同样的state: AssetRenderState = {}对于一个 HTML 响应,即使内容被重新生成。 打电话renderHeadContent每个 HTML 响应一次。 Bootstrap一次被放出;其初始配置适用于整个响应. 直接content.helpers呼叫生成普通标记而不进行倒置处理. - 流出时,样式表的
timeoutMs当引用到达 HTML 时开始。 无法找到的已注册样式表链接DOMContentLoaded被报告为失败,而不阻断脚本.
import {renderHeadContent, renderScripts, type AssetRenderState} from '@gravity-ui/app-layout';
const state: AssetRenderState = {};
res.write(renderScripts(content, firstScripts, state));
// ... await data and regenerate content if needed.
res.write(renderHeadContent(content, state));
懒散块需要单独的配置,例如 client.publicPathFallback 内 应用程序构建器。配置两个库中的备份地址;不通过全局变量共享后退列表.
@ gravity-ui/ wiikit (重力- iikit )
添加身体属性.
用法 :
import {createRenderFunction, createUikitPlugin} from '@gravity-ui/app-layout';
const renderLayout = createRenderFunction([createUikitPlugin()]);
app.get((req, res) => {
res.send(
renderLayout({
title: 'Home page',
pluginsOptions: {
uikit: {
theme: 'dark',
direction: 'ltr',
},
},
}),
);
});
插件选项 :
interface UikitPluginOptions {
theme: string;
direction?: 'ltr' | 'rtl';
}
远程版本
向页面添加微前端版本信息.
此插件创建全局 window.__REMOTE_VERSIONS__ 对象包含提供的微前端版本,可以被模块front或类似的微前端架构所使用,以确定要加载的远程模块的哪些版本.
它可以结合使用 应用程序构建器 编辑 moduleFederation.remotesRuntimeVersioning 选项可以自动加载带有相应版本的远程模块.
用法 :
import {createRenderFunction, createRemoteVersionsPlugin} from '@gravity-ui/app-layout';
const renderLayout = createRenderFunction([createRemoteVersionsPlugin()]);
app.get((req, res) => {
res.send(
renderLayout({
title: 'Home page',
pluginsOptions: {
remoteVersions: {
header: '1.2.3',
footer: '2.1.0',
sidebar: '0.5.1',
},
},
}),
);
});
插件选项 :
type RemoteVersionsPluginOptions = Record<string, string>;
帮助者
创建所有插件的助手 :
import {createMiddleware, createDefaultPlugins} from '@gravity-ui/app-layout';
const renderLayout = createRenderFunction(
createDefaultPlugins({layout: {manifest: 'path/to/assets-manifest.json'}})
);
app.get((req, res) => {
res.send(renderLayout({
title: 'Home page',
pluginsOptions: {
layout: {
name: 'home'
},
googleAnalytics: {
counter: {...}
},
yandexMetrika: {
counter: {...}
},
},
}));
})
替代用途
用零件渲染器 generateRenderContent, (中文(简体) ), renderHeadContent, (中文(简体) ), renderBodyContent 通过 html 流线:
import express from 'express';
import htmlescape from 'htmlescape';
import {
generateRenderContent,
renderHeadContent,
renderBodyContent,
createDefaultPlugins,
} from '@gravity-ui/app-layout';
const app = express();
app.get('/', async function (req, res) {
res.writeHead(200, {
'Content-Type': 'text/html',
'Transfer-Encoding': 'chunked',
});
const plugins = createDefaultPlugins({layout: {manifest: 'path/to/assets-manifest.json'}});
const content = generateRenderContent(plugins, {
title: 'Home page',
});
const {htmlAttributes, helpers, bodyContent} = content;
res.write(`
<!DOCTYPE html>
<html ${helpers.attrs({...htmlAttributes})}>
<head>
${renderHeadContent(content)}
</head>
<body ${helpers.attrs(bodyContent.attributes)}>
${renderBodyContent(content)}
`);
const data = await getUserData();
res.write(`
${content.renderHelpers.renderInlineScript(`
window.__DATA__ = ${htmlescape(data)};
`)}
</body>
</html>
`);
res.end();
});
app.listen(3000);