Unverified Commit 6124e7d2 authored by Henrik Wenz's avatar Henrik Wenz Committed by GitHub

Update with-react-intl example (#28336)

This PR implements Internationalized Routing using formatjs / react-intl.

## Changelog

- Updated formatjs to latest version
- Remove  deprecated babel-react-intl-plugin in favor of babel-formatjs-plugin
- Remove server in favour of Internationalized Routing
- Added linter with formatjs rules
- Refactored JSX
- Added missing types
- Auto run formtjs script via before hooks
- Adjusted readme docs
- Added message descriptions
- Removed default configs



fixes #27870

## Bug

- [x] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [x] Make sure the linting passes
parent 5b963422
...@@ -2,11 +2,9 @@ ...@@ -2,11 +2,9 @@
"presets": ["next/babel"], "presets": ["next/babel"],
"plugins": [ "plugins": [
[ [
"babel-plugin-react-intl", "formatjs",
{ {
"ast": true, "ast": true
"idInterpolationPattern": "[sha512:contenthash:base64:6]",
"extractFromFormatMessageCall": true
} }
] ]
] ]
......
{
"extends": "next",
"plugins": ["formatjs"],
"root": true,
"rules": {
"formatjs/enforce-default-message": ["error", "literal"]
}
}
...@@ -16,17 +16,21 @@ Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&ut ...@@ -16,17 +16,21 @@ Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&ut
## Features of this example app ## Features of this example app
- Server-side language negotiation
- React Intl locale data loading via `pages/_document.js` customization
- React Intl integration with [custom App](https://github.com/vercel/next.js#custom-app) component - React Intl integration with [custom App](https://github.com/vercel/next.js#custom-app) component
- `<IntlProvider>` creation with `locale`, `messages` props - `<IntlProvider>` creation with `locale`, `messages` props
- Default message extraction via `@formatjs/cli` integration - Default message extraction via `@formatjs/cli` integration
- Pre-compile messages into AST with `babel-plugin-react-intl` for performance - Pre-compile messages into AST with `babel-plugin-formatjs` for performance
- Translation management via build script and customized Next server - Translation management
### Translation Management ### Translation Management
This app stores translations and default strings in the `lang/` dir. The default messages (`en.json` in this example app) is also generated by the build script. This file can then be sent to a translation service to perform localization for the other locales the app should support. This app stores translations and default strings in the `lang/` dir. The default messages (`en.json` in this example app) is also generated by the following script.
```bash
$ npm run i18n:extract
```
This file can then be sent to a translation service to perform localization for the other locales the app should support.
The translated messages files that exist at `lang/*.json` are only used during production, and are automatically provided to the `<IntlProvider>`. During development the `defaultMessage`s defined in the source code are used. To prepare the example app for localization and production run the build script and start the server in production mode: The translated messages files that exist at `lang/*.json` are only used during production, and are automatically provided to the `<IntlProvider>`. During development the `defaultMessage`s defined in the source code are used. To prepare the example app for localization and production run the build script and start the server in production mode:
...@@ -35,6 +39,6 @@ $ npm run build ...@@ -35,6 +39,6 @@ $ npm run build
$ npm start $ npm start
``` ```
You can then switch your browser's language preferences to French and refresh the page to see the UI update accordingly. You can then switch your browser's language preferences to German or French and refresh the page to see the UI update accordingly.
[react intl]: https://formatjs.io [react intl]: https://formatjs.io
import * as React from 'react'; import { ReactChild } from 'react'
import {useIntl} from 'react-intl'; import { useIntl } from 'react-intl'
import Head from 'next/head'; import Head from 'next/head'
import Nav from './Nav'; import Nav from './Nav'
export default function Layout({title, children}) { interface LayoutProps {
const intl = useIntl(); title?: string
description?: string
children: ReactChild | ReactChild[]
}
export default function Layout({ title, description, children }: LayoutProps) {
const intl = useIntl()
return ( return (
<div> <>
<Head> <Head>
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<title> <title>
{title || {title ||
intl.formatMessage({ intl.formatMessage({
defaultMessage: 'React Intl Next.js Example', defaultMessage: 'React Intl Next.js Example',
description: 'Default document title',
})}
{description ||
intl.formatMessage({
defaultMessage: 'This page is powered by Next.js',
description: 'Default document description',
})} })}
</title> </title>
</Head> </Head>
<header> <header>
<Nav /> <Nav />
</header> </header>
{children} {children}
</div> </>
); )
} }
.nav {
display: flex;
}
.li {
list-style: none;
margin-right: 1rem;
}
.active {
color: red;
}
.divider {
list-style: none;
width: 1px;
margin-right: 1rem;
background: black;
margin-left: auto;
}
import * as React from 'react'; import Link from 'next/link'
import {FormattedMessage} from 'react-intl'; import { useRouter } from 'next/router'
import Link from 'next/link'; import { FormattedMessage } from 'react-intl'
import styles from './Nav.module.css'
export default function Nav() { export default function Nav() {
const { locale, locales, asPath } = useRouter()
return ( return (
<nav> <nav className={styles.nav}>
<li> <li className={styles.li}>
<Link href="/"> <Link href="/" passHref>
<a> <a>
<FormattedMessage defaultMessage="Home" /> <FormattedMessage
defaultMessage="Home"
description="Nav: Index name"
/>
</a> </a>
</Link> </Link>
</li> </li>
<li> <li className={styles.li}>
<Link href="/about"> <Link href="/about" passHref>
<a> <a>
<FormattedMessage defaultMessage="About" /> <FormattedMessage
defaultMessage="About"
description="Nav: About item"
/>
</a> </a>
</Link> </Link>
</li> </li>
<style jsx>{` <li className={styles.divider}></li>
nav {
display: flex; {locales.map((availableLocale) => (
} <li key={availableLocale} className={styles.li}>
li { <Link
list-style: none; href={asPath}
margin-right: 1rem; locale={availableLocale}
} passHref
`}</style> prefetch={false}
>
<a
className={availableLocale === locale ? styles.active : undefined}
>
{availableLocale}
</a>
</Link>
</li>
))}
</nav> </nav>
); )
} }
import fs from 'fs/promises'
import path from 'path'
type LoadI18nMessagesProps = {
locale: string
defaultLocale: string
}
type MessageConfig = { [key: string]: string }
export default async function loadI18nMessages({
locale,
defaultLocale,
}: LoadI18nMessagesProps): Promise<MessageConfig> {
// If the default locale is being used we can skip it
if (locale === defaultLocale) {
return {}
}
if (locale !== defaultLocale) {
const languagePath = path.join(
process.cwd(),
`compiled-lang/${locale}.json`
)
try {
const contents = await fs.readFile(languagePath, 'utf-8')
return JSON.parse(contents)
} catch (error) {
console.info(
'Could not load compiled language files. Please run "npm run i18n:compile" first"'
)
console.error(error)
}
}
}
{
"9CBSZS": {
"defaultMessage": "Eine Beispiel-App, die React Intl mit Next.js integriert.",
"description": "Index Page: Meta Description"
},
"I0B7AG": {
"defaultMessage": "Hallo, Welt!",
"description": "Index Page: Content"
},
"Lg2S9x": {
"defaultMessage": "React Intl Next.js Beispiel",
"description": "Default document title"
},
"Ml7614": {
"defaultMessage": "Start",
"description": "Nav: Index name"
},
"WIATrC": {
"defaultMessage": "Diese Seite wird mit Next.js betrieben",
"description": "Default document description"
},
"lyiQWH": {
"defaultMessage": "Start",
"description": "Index Page: document title"
},
"n5ul5I": {
"defaultMessage": "Über",
"description": "Nav: About item"
}
}
{
"AvQcw8": "React Intl Next.js Example, in en-GB",
"N015Sp": "Hello, World, from the UK!",
"ejEGdx": "Home (British version)",
"fnfXnF": "An example app integrating React Intl with Next.js",
"g5pX+a": "About (British version)"
}
{ {
"AvQcw8": "React Intl Next.js Example", "9CBSZS": {
"N015Sp": "Hello, World!", "defaultMessage": "An example app integrating React Intl with Next.js",
"ejEGdx": "Home", "description": "Index Page: Meta Description"
"fnfXnF": "An example app integrating React Intl with Next.js", },
"g5pX+a": "About" "I0B7AG": {
"defaultMessage": "Hello, World!",
"description": "Index Page: Content"
},
"Lg2S9x": {
"defaultMessage": "React Intl Next.js Example",
"description": "Default document title"
},
"Ml7614": {
"defaultMessage": "Home",
"description": "Nav: Index name"
},
"WIATrC": {
"defaultMessage": "This page is powered by Next.js",
"description": "Default document description"
},
"lyiQWH": {
"defaultMessage": "Home",
"description": "Index Page: document title"
},
"n5ul5I": {
"defaultMessage": "About",
"description": "Nav: About item"
}
} }
{ {
"AvQcw8": "React Intl Next.js Exemple", "9CBSZS": {
"N015Sp": "Bonjour le monde!", "defaultMessage": "Un exemple d'application intégrant React Intl avec Next.js",
"ejEGdx": "Accueil", "description": "Index Page: Meta Description"
"fnfXnF": "Un exemple d'application intégrant React Intl avec Next.js", },
"g5pX+a": "À propos de nous" "I0B7AG": {
"defaultMessage": "Bonjour le monde!",
"description": "Index Page: Content"
},
"Lg2S9x": {
"defaultMessage": "React Intl Next.js Exemple",
"description": "Default document title"
},
"Ml7614": {
"defaultMessage": "Accueil",
"description": "Nav: Index name"
},
"WIATrC": {
"defaultMessage": "Cette page est propulsée par Next.js",
"description": "Default document description"
},
"lyiQWH": {
"defaultMessage": "Accueil",
"description": "Index Page: document title"
},
"n5ul5I": {
"defaultMessage": "À propos de nous",
"description": "Nav: About item"
}
} }
{
"AvQcw8": " React Intl Next.js示例",
"N015Sp": "你好,世界!",
"ejEGdx": "首页",
"fnfXnF": "一个将React Intl与Next.js集成的示例应用程序",
"g5pX+a": "关于"
}
{
"AvQcw8": "React Intl Next.js示例",
"N015Sp": "你好,世界!",
"ejEGdx": "首頁",
"fnfXnF": "一個將React Intl與Next.js集成的示例應用程序",
"g5pX+a": "關於"
}
// @ts-check
/**
* @type {import('next').NextConfig}
**/
module.exports = {
i18n: {
locales: ['en', 'fr', 'de'],
defaultLocale: 'en',
},
webpack(config, { dev, ...other }) {
if (!dev) {
// https://formatjs.io/docs/guides/advanced-usage#react-intl-without-parser-40-smaller
config.resolve.alias['@formatjs/icu-messageformat-parser'] =
'@formatjs/icu-messageformat-parser/no-parser'
}
return config
},
}
{ {
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "cross-env NODE_ICU_DATA=node_modules/full-icu ts-node --project tsconfig.server.json server.ts", "predev": "npm run i18n:compile",
"dev-no-custom-server": "next dev", "dev": "next dev",
"build": "npm run extract:i18n && npm run compile:i18n && next build && tsc -p tsconfig.server.json", "prebuild": "npm run i18n:compile",
"extract:i18n": "formatjs extract '{pages,components}/**/*.{js,ts,tsx}' --format simple --id-interpolation-pattern '[sha512:contenthash:base64:6]' --out-file lang/en.json", "build": "next build",
"compile:i18n": "formatjs compile-folder --ast --format simple lang compiled-lang", "start": "next start",
"start": "cross-env NODE_ENV=production NODE_ICU_DATA=node_modules/full-icu node dist/server", "lint": "next lint",
"start-no-custom-server": "next start" "i18n:extract": "formatjs extract 'pages/**/*.ts*' 'components/**/*.ts*' --out-file lang/en.json",
"i18n:compile": "formatjs compile-folder lang compiled-lang"
}, },
"dependencies": { "dependencies": {
"@formatjs/cli": "^2.7.3", "next": "11.1.0",
"@formatjs/intl-datetimeformat": "^2.4.3", "react": "17.0.2",
"@formatjs/intl-getcanonicallocales": "^1.3.2", "react-dom": "17.0.2",
"@formatjs/intl-numberformat": "^5.4.1", "react-intl": "5.20.9"
"@formatjs/intl-pluralrules": "^3.4.0",
"@formatjs/intl-relativetimeformat": "^7.1.1",
"accepts": "^1.3.7",
"babel-plugin-react-intl": "^8.1.1",
"cross-env": "^7.0.2",
"full-icu": "^1.3.0",
"glob": "^7.1.4",
"next": "latest",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-intl": "^5.6.3"
}, },
"devDependencies": { "devDependencies": {
"@types/accepts": "^1.3.5", "@formatjs/cli": "4.2.31",
"cross-spawn": "7.0.3", "@types/node": "16.6.2",
"prettier": "2.0.5", "@types/react": "17.0.19",
"ts-node": "8.0.1", "@types/styled-jsx": "3.4.4",
"typescript": "4.0" "babel-plugin-formatjs": "10.3.5",
}, "eslint-plugin-formatjs": "2.17.4",
"prettier": { "typescript": "4.3.5"
"singleQuote": true,
"trailingComma": "es5",
"bracketSpacing": false,
"endOfLine": "lf",
"arrowParens": "avoid"
} }
} }
import * as React from 'react'; import type { AppProps } from 'next/app'
import {IntlProvider} from 'react-intl'; import { IntlProvider } from 'react-intl'
import {polyfill} from '../polyfills'; import { useRouter } from 'next/router'
import App from 'next/app';
function MyApp({Component, pageProps, locale, messages}) { export default function MyApp({ Component, pageProps }: AppProps) {
const { locale, defaultLocale } = useRouter()
return ( return (
<IntlProvider locale={locale} defaultLocale="en" messages={messages}> <IntlProvider
locale={locale}
defaultLocale={defaultLocale}
messages={pageProps.intlMessages}
>
<Component {...pageProps} /> <Component {...pageProps} />
</IntlProvider> </IntlProvider>
); )
} }
/**
* Get the messages and also do locale negotiation. A multi-lingual user
* can specify locale prefs like ['ja', 'en-GB', 'en'] which is interpreted as
* Japanese, then British English, then English
* @param locales list of requested locales
* @returns {[string, Promise]} A tuple containing the negotiated locale
* and the promise of fetching the translated messages
*/
function getMessages(locales: string | string[] = ['en']) {
if (!Array.isArray(locales)) {
locales = [locales];
}
let langBundle;
let locale;
for (let i = 0; i < locales.length && !locale; i++) {
locale = locales[i];
switch (locale) {
case 'fr':
langBundle = import('../compiled-lang/fr.json');
break;
case 'en-GB':
langBundle = import('../compiled-lang/en-GB.json');
break;
case 'zh-Hans-CN':
langBundle = import('../compiled-lang/zh-Hans-CN.json');
break;
case 'zh-Hant-HK':
langBundle = import('../compiled-lang/zh-Hant-HK.json');
break;
default:
break;
// Add more languages
}
}
if (!langBundle) {
return ['en', import('../compiled-lang/en.json')];
}
return [locale, langBundle];
}
const getInitialProps: typeof App.getInitialProps = async appContext => {
const {
ctx: {req},
} = appContext;
const requestedLocales: string | string[] =
(req as any)?.locale ||
(typeof navigator !== 'undefined' && navigator.languages) ||
// IE11
(typeof navigator !== 'undefined' && (navigator as any).userLanguage) ||
(typeof window !== 'undefined' && (window as any).LOCALE) ||
'en';
const [supportedLocale, messagePromise] = getMessages(requestedLocales);
const [, messages, appProps] = await Promise.all([
polyfill(supportedLocale),
messagePromise,
App.getInitialProps(appContext),
]);
return {
...(appProps as any),
locale: supportedLocale,
messages: messages.default,
};
};
MyApp.getInitialProps = getInitialProps;
export default MyApp;
import Document, {
Html,
Head,
Main,
NextScript,
DocumentContext,
} from 'next/document';
interface Props {
locale: string;
lang: string;
nonce: string;
}
class MyDocument extends Document<Props> {
static async getInitialProps(ctx: DocumentContext) {
const {req} = ctx;
const initialProps = await Document.getInitialProps(ctx);
const locale = (req as any).locale;
return {
...initialProps,
locale,
lang: locale ? locale.split('-')[0] : undefined,
nonce: (req as any).nonce,
};
}
render() {
let scriptEl;
if (this.props.locale) {
scriptEl = (
<script
nonce={this.props.nonce}
dangerouslySetInnerHTML={{
__html: `window.LOCALE="${this.props.locale}"`,
}}
></script>
);
}
return (
<Html lang={this.props.lang}>
<Head />
<body>
{scriptEl}
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
import * as React from 'react'; import { FormattedRelativeTime, useIntl } from 'react-intl'
import {FormattedRelativeTime, useIntl} from 'react-intl'; import Layout from '../components/Layout'
import Layout from '../components/Layout'; import loadIntlMessages from '../helper/loadIntlMessages'
import { InferGetStaticPropsType } from 'next'
export default function About() { export async function getStaticProps(ctx) {
const intl = useIntl(); return {
props: {
intlMessages: await loadIntlMessages(ctx),
},
}
}
type AboutPageProps = InferGetStaticPropsType<typeof getStaticProps>
export default function AboutPage(props: AboutPageProps) {
const intl = useIntl()
return ( return (
<Layout title={intl.formatMessage({defaultMessage: 'About'})}> <Layout
title={intl.formatMessage({
defaultMessage: 'About',
description: 'Nav: About item',
})}
>
<p> <p>
<FormattedRelativeTime numeric="auto" value={1} unit="hour" /> <FormattedRelativeTime numeric="auto" value={1} unit="hour" />
</p> </p>
</Layout> </Layout>
); )
} }
import * as React from 'react'; import { FormattedMessage, FormattedNumber, useIntl } from 'react-intl'
import {FormattedMessage, FormattedNumber, useIntl} from 'react-intl'; import Layout from '../components/Layout'
import Head from 'next/head'; import loadIntlMessages from '../helper/loadIntlMessages'
import Layout from '../components/Layout'; import { InferGetStaticPropsType } from 'next'
export default function Home() { export async function getStaticProps(ctx) {
const intl = useIntl(); return {
props: {
intlMessages: await loadIntlMessages(ctx),
},
}
}
type HomePageProps = InferGetStaticPropsType<typeof getStaticProps>
export default function HomePage(props: HomePageProps) {
const intl = useIntl()
return ( return (
<Layout <Layout
title={intl.formatMessage({ title={intl.formatMessage({
defaultMessage: 'Home', defaultMessage: 'Home',
description: 'Index Page: document title',
})} })}
> description={intl.formatMessage({
<Head> defaultMessage: 'An example app integrating React Intl with Next.js',
<meta description: 'Index Page: Meta Description',
name="description"
content={intl.formatMessage({
defaultMessage:
'An example app integrating React Intl with Next.js',
})} })}
/> >
</Head>
<p> <p>
<FormattedMessage defaultMessage="Hello, World!" /> <FormattedMessage
defaultMessage="Hello, World!"
description="Index Page: Content"
/>
</p> </p>
<p> <p>
<FormattedNumber value={1000} /> <FormattedNumber value={1000} />
</p> </p>
</Layout> </Layout>
); )
} }
import {shouldPolyfill as shouldPolyfillGetCanonicalLocales} from '@formatjs/intl-getcanonicallocales/should-polyfill';
import {shouldPolyfill as shouldPolyfillPluralRules} from '@formatjs/intl-pluralrules/should-polyfill';
import {shouldPolyfill as shouldPolyfillNumberFormat} from '@formatjs/intl-numberformat/should-polyfill';
import {shouldPolyfill as shouldPolyfillDateTimeFormat} from '@formatjs/intl-datetimeformat/should-polyfill';
import {shouldPolyfill as shouldPolyfillRelativeTimeFormat} from '@formatjs/intl-relativetimeformat/should-polyfill';
/**
* Dynamically polyfill Intl API & its locale data
* @param locale locale to polyfill
*/
export async function polyfill(locale: string = '') {
const dataPolyfills = [];
// Polyfill Intl.getCanonicalLocales if necessary
if (shouldPolyfillGetCanonicalLocales()) {
await import(
/* webpackChunkName: "intl-getcanonicallocales" */ '@formatjs/intl-getcanonicallocales/polyfill'
);
}
// Polyfill Intl.PluralRules if necessary
if (shouldPolyfillPluralRules()) {
await import(
/* webpackChunkName: "intl-pluralrules" */ '@formatjs/intl-pluralrules/polyfill'
);
}
if ((Intl.PluralRules as any).polyfilled) {
const lang = locale.split('-')[0];
switch (lang) {
default:
dataPolyfills.push(
import(
/* webpackChunkName: "intl-pluralrules" */ '@formatjs/intl-pluralrules/locale-data/en'
)
);
break;
case 'fr':
dataPolyfills.push(
import(
/* webpackChunkName: "intl-pluralrules" */ '@formatjs/intl-pluralrules/locale-data/fr'
)
);
break;
}
}
// Polyfill Intl.NumberFormat if necessary
if (shouldPolyfillNumberFormat()) {
await import(
/* webpackChunkName: "intl-numberformat" */ '@formatjs/intl-numberformat/polyfill'
);
}
if ((Intl.NumberFormat as any).polyfilled) {
switch (locale) {
default:
dataPolyfills.push(
import(
/* webpackChunkName: "intl-numberformat" */ '@formatjs/intl-numberformat/locale-data/en'
)
);
break;
case 'fr':
dataPolyfills.push(
import(
/* webpackChunkName: "intl-numberformat" */ '@formatjs/intl-numberformat/locale-data/fr'
)
);
break;
}
}
// Polyfill Intl.DateTimeFormat if necessary
if (shouldPolyfillDateTimeFormat()) {
await import(
/* webpackChunkName: "intl-datetimeformat" */ '@formatjs/intl-datetimeformat/polyfill'
);
}
if ((Intl.DateTimeFormat as any).polyfilled) {
dataPolyfills.push(import('@formatjs/intl-datetimeformat/add-all-tz'));
switch (locale) {
default:
dataPolyfills.push(
import(
/* webpackChunkName: "intl-datetimeformat" */ '@formatjs/intl-datetimeformat/locale-data/en'
)
);
break;
case 'fr':
dataPolyfills.push(
import(
/* webpackChunkName: "intl-datetimeformat" */ '@formatjs/intl-datetimeformat/locale-data/fr'
)
);
break;
}
}
// Polyfill Intl.RelativeTimeFormat if necessary
if (shouldPolyfillRelativeTimeFormat()) {
await import(
/* webpackChunkName: "intl-relativetimeformat" */ '@formatjs/intl-relativetimeformat/polyfill'
);
}
if ((Intl as any).RelativeTimeFormat.polyfilled) {
switch (locale) {
default:
dataPolyfills.push(
import(
/* webpackChunkName: "intl-relativetimeformat" */ '@formatjs/intl-relativetimeformat/locale-data/en'
)
);
break;
case 'fr':
dataPolyfills.push(
import(
/* webpackChunkName: "intl-relativetimeformat" */ '@formatjs/intl-relativetimeformat/locale-data/fr'
)
);
break;
}
}
await Promise.all(dataPolyfills);
}
import {basename} from 'path';
import {sync as globSync} from 'glob';
import {createServer} from 'http';
import accepts from 'accepts';
import next from 'next';
import {polyfill} from './polyfills';
import crypto from 'crypto';
// Get the supported languages by looking for translations in the `lang/` dir.
const supportedLanguages = globSync('./compiled-lang/*.json').map(f =>
basename(f, '.json')
);
const SUPPORTED_LOCALES = ['en', 'fr'];
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({dev});
const handle = app.getRequestHandler();
Promise.all([app.prepare(), ...SUPPORTED_LOCALES.map(polyfill)]).then(() => {
createServer((req, res) => {
const accept = accepts(req);
const locale = accept.language(supportedLanguages) || 'en';
(req as any).locale = locale;
const nonce = crypto.randomBytes(20).toString('hex');
(req as any).nonce = nonce;
// TODO: This will blow up other next inline JS but next.js should prob fix this
// res.setHeader('Content-Security-Policy', `script-src 'nonce-${nonce}'`);
handle(req, res);
}).listen(port, () => {
console.log(`> Ready on http://localhost:${port}`);
});
});
{ {
"compilerOptions": { "compilerOptions": {
"jsx": "preserve", "incremental": true,
"target": "es5", "target": "es5",
"lib": ["dom", "dom.iterable", "esnext", "ESNext.Intl", "ES2018.Intl"], "lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true, "allowJs": true,
"skipLibCheck": true, "skipLibCheck": true,
"strict": false, "strict": false,
...@@ -12,7 +12,8 @@ ...@@ -12,7 +12,8 @@
"module": "esnext", "module": "esnext",
"moduleResolution": "node", "moduleResolution": "node",
"resolveJsonModule": true, "resolveJsonModule": true,
"isolatedModules": true "isolatedModules": true,
"jsx": "preserve"
}, },
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"] "exclude": ["node_modules"]
......
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "dist",
"module": "CommonJS",
"noEmit": false
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment