Unverified Commit 009b6a19 authored by Janicklas Ralph's avatar Janicklas Ralph Committed by GitHub

Setting up third-parties package (#51194)

This PR Introduces `next/third-parties`

- `@next/third-parties` is a new package in the Next.js monorepo. 
- The package contains collection of components that can be used to
efficiently load third party libraries into your Next.js application.
- This package uses [Third Party
Capital](https://github.com/GoogleChromeLabs/third-party-capital/) under
the hood to fetch the best loading recommendations.
- This PR mainly sets up the package to run a script at build time to
auto generate the components from [Third Party
Capital](https://github.com/GoogleChromeLabs/third-party-capital/)
config.

Packages are grouped by company, for eg:

`import { GoogleMapsEmbed } from '@next/third-parties/google'`


cc: @housseindjirdeh @kara 
<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md



## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->

---------
parent 2cea3f70
...@@ -73,6 +73,7 @@ ...@@ -73,6 +73,7 @@
"@next/env": "workspace:*", "@next/env": "workspace:*",
"@next/eslint-plugin-next": "workspace:*", "@next/eslint-plugin-next": "workspace:*",
"@next/font": "workspace:*", "@next/font": "workspace:*",
"@next/third-parties": "workspace:*",
"@next/mdx": "workspace:*", "@next/mdx": "workspace:*",
"@next/plugin-storybook": "workspace:*", "@next/plugin-storybook": "workspace:*",
"@next/polyfill-module": "workspace:*", "@next/polyfill-module": "workspace:*",
......
...@@ -17,6 +17,7 @@ export interface ScriptProps extends ScriptHTMLAttributes<HTMLScriptElement> { ...@@ -17,6 +17,7 @@ export interface ScriptProps extends ScriptHTMLAttributes<HTMLScriptElement> {
onReady?: () => void | null onReady?: () => void | null
onError?: (e: any) => void onError?: (e: any) => void
children?: React.ReactNode children?: React.ReactNode
stylesheets?: string[]
} }
/** /**
...@@ -31,8 +32,42 @@ const ignoreProps = [ ...@@ -31,8 +32,42 @@ const ignoreProps = [
'children', 'children',
'onError', 'onError',
'strategy', 'strategy',
'stylesheets',
] ]
const insertStylesheets = (stylesheets: string[]) => {
// Case 1: Styles for afterInteractive/lazyOnload with appDir injected via handleClientScriptLoad
//
// Using ReactDOM.preinit to feature detect appDir and inject styles
// Stylesheets might have already been loaded if initialized with Script component
// Re-inject styles here to handle scripts loaded via handleClientScriptLoad
// ReactDOM.preinit handles dedup and ensures the styles are loaded only once
if (ReactDOM.preinit) {
stylesheets.forEach((stylesheet: string) => {
ReactDOM.preinit(stylesheet, { as: 'style' })
})
return
}
// Case 2: Styles for afterInteractive/lazyOnload with pages injected via handleClientScriptLoad
//
// We use this function to load styles when appdir is not detected
// TODO: Use React float APIs to load styles once available for pages dir
if (typeof window !== 'undefined') {
let head = document.head
stylesheets.forEach((stylesheet: string) => {
let link = document.createElement('link')
link.type = 'text/css'
link.rel = 'stylesheet'
link.href = stylesheet
head.appendChild(link)
})
}
}
const loadScript = (props: ScriptProps): void => { const loadScript = (props: ScriptProps): void => {
const { const {
src, src,
...@@ -43,6 +78,7 @@ const loadScript = (props: ScriptProps): void => { ...@@ -43,6 +78,7 @@ const loadScript = (props: ScriptProps): void => {
children = '', children = '',
strategy = 'afterInteractive', strategy = 'afterInteractive',
onError, onError,
stylesheets,
} = props } = props
const cacheKey = id || src const cacheKey = id || src
...@@ -127,6 +163,11 @@ const loadScript = (props: ScriptProps): void => { ...@@ -127,6 +163,11 @@ const loadScript = (props: ScriptProps): void => {
el.setAttribute('data-nscript', strategy) el.setAttribute('data-nscript', strategy)
// Load styles associated with this script
if (stylesheets) {
insertStylesheets(stylesheets)
}
document.body.appendChild(el) document.body.appendChild(el)
} }
...@@ -175,6 +216,7 @@ function Script(props: ScriptProps): JSX.Element | null { ...@@ -175,6 +216,7 @@ function Script(props: ScriptProps): JSX.Element | null {
onReady = null, onReady = null,
strategy = 'afterInteractive', strategy = 'afterInteractive',
onError, onError,
stylesheets,
...restProps ...restProps
} = props } = props
...@@ -259,6 +301,21 @@ function Script(props: ScriptProps): JSX.Element | null { ...@@ -259,6 +301,21 @@ function Script(props: ScriptProps): JSX.Element | null {
// For the app directory, we need React Float to preload these scripts. // For the app directory, we need React Float to preload these scripts.
if (appDir) { if (appDir) {
// Injecting stylesheets here handles beforeInteractive and worker scripts correctly
// For other strategies injecting here ensures correct stylesheet order
// ReactDOM.preinit handles loading the styles in the correct order,
// also ensures the stylesheet is loaded only once and in a consistent manner
//
// Case 1: Styles for beforeInteractive/worker with appDir - handled here
// Case 2: Styles for beforeInteractive/worker with pages dir - Not handled yet
// Case 3: Styles for afterInteractive/lazyOnload with appDir - handled here
// Case 4: Styles for afterInteractive/lazyOnload with pages dir - handled in insertStylesheets function
if (stylesheets) {
stylesheets.forEach((styleSrc) => {
ReactDOM.preinit(styleSrc, { as: 'style' })
})
}
// Before interactive scripts need to be loaded by Next.js' runtime instead // Before interactive scripts need to be loaded by Next.js' runtime instead
// of native <script> tags, because they no longer have `defer`. // of native <script> tags, because they no longer have `defer`.
if (strategy === 'beforeInteractive') { if (strategy === 'beforeInteractive') {
...@@ -282,8 +339,7 @@ function Script(props: ScriptProps): JSX.Element | null { ...@@ -282,8 +339,7 @@ function Script(props: ScriptProps): JSX.Element | null {
}} }}
/> />
) )
} } else {
// @ts-ignore // @ts-ignore
ReactDOM.preload( ReactDOM.preload(
src, src,
...@@ -301,6 +357,7 @@ function Script(props: ScriptProps): JSX.Element | null { ...@@ -301,6 +357,7 @@ function Script(props: ScriptProps): JSX.Element | null {
}} }}
/> />
) )
}
} else if (strategy === 'afterInteractive') { } else if (strategy === 'afterInteractive') {
if (src) { if (src) {
// @ts-ignore // @ts-ignore
......
{
"name": "@next/third-parties",
"version": "13.4.5-canary.8",
"private": true,
"repository": {
"url": "vercel/next.js",
"directory": "packages/third-parties"
},
"main": "dist/index.js",
"files": [
"dist"
],
"license": "MIT",
"scripts": {
"build": "rm -rf dist && tsc -d -p tsconfig.json && node scripts/update-third-parties",
"prepublishOnly": "cd ../../ && turbo run build",
"dev": "tsc -d -w -p tsconfig.json",
"typescript": "tsec --noEmit -p tsconfig.json"
},
"dependencies": {
"third-party-capital": "1.0.17"
},
"devDependencies": {
"outdent": "0.8.0",
"prettier": "2.5.1"
},
"peerDependencies": {
"next": "^13.0.0",
"react": "^18.2.0"
}
}
const fs = require('fs/promises')
const path = require('path')
const AllThirdParties = require('third-party-capital')
// eslint-disable-next-line import/no-extraneous-dependencies
const prettier = require('prettier')
// eslint-disable-next-line import/no-extraneous-dependencies
const { outdent } = require('outdent')
const scriptStrategy = {
server: 'beforeInteractive',
client: 'afterInteractive',
idle: 'lazyOnload',
worker: 'worker',
}
const SRC = path.join(__dirname, '../src')
const CONFIG_FILE_NAME = 'tpc-config.json'
function generateComponent(thirdParty) {
let thirdPartyFunctions = ''
const insertScripts = (id, scripts, stylesheets) => {
let props = ''
if (stylesheets?.length > 0) {
props += ` stylesheets={${JSON.stringify(stylesheets)}}`
}
return scripts
.map((script) => {
if (typeof script === 'string') {
// External script with only URL
return `<Script src="${script}"${props} />`
} else if (script.url) {
// External script with additional properties
// TODO: Validate the strategy. Set fallback if an inpnpvalid strategy is passed
const { url, strategy } = script
return `<Script src={\`${url}\`} strategy="${scriptStrategy[strategy]}"${props} />`
} else if (script.code) {
// Inline script with additional properties
const { code, strategy } = script
return outdent`<Script
id="${id}"
strategy="${scriptStrategy[strategy]}"
dangerouslySetInnerHTML={{
__html: \`${code}\`,
}}${props}
/>`
}
return ''
})
.join('')
}
const { id, description, content, scripts, stylesheets } =
AllThirdParties[thirdParty]
thirdPartyFunctions += outdent`
// ${description}
export function ${thirdParty}(args: any) {
return (
<Base
${content ? 'height={args.height || null}' : ''}
${content ? 'width={args.width || null}' : ''}
${content ? `content={\`${content}\`}` : ''}>
${scripts?.length > 0 ? insertScripts(id, scripts, stylesheets) : ''}
</Base>
)
}
`
return thirdPartyFunctions
}
;(async () => {
const dirs = (await fs.readdir(SRC, { withFileTypes: true }))
.filter((dirent) => dirent.isDirectory())
.map((dirent) => dirent.name)
for (let dir of dirs) {
// Fetch the list of third-parties from tpc-config.json
// Then retrieve its loading instructions from Third Party Capital
const dirPath = path.join(SRC, dir)
const configFile = (await fs.readdir(dirPath)).find(
(file) => file === CONFIG_FILE_NAME
)
if (!configFile) continue
const config = JSON.parse(await fs.readFile(path.join(dirPath, configFile)))
let thirdPartyFunctions = `/**
* This is an autogenerated file by update-third-parties.js
*/
import React from 'react'
import Script from 'next/script'
import Base from './base'
`
for (const thirdParty of Object.values(config)) {
thirdPartyFunctions += generateComponent(thirdParty)
}
await Promise.all([
fs.writeFile(
path.join(dirPath, 'index.tsx'),
prettier.format(thirdPartyFunctions, { semi: false, parser: 'babel' })
),
])
}
})()
import React from 'react'
export default function Base({
content,
height = null,
width = null,
children,
}: {
content?: string
height?: number | null
width?: number | null
children?: React.ReactElement | React.ReactElement[]
}) {
return (
<>
{/* insert script children */}
{children}
{/* insert content */}
{content && (
<div
style={{
height: height != null ? `${height}px` : 'auto',
width: width != null ? `${width}px` : 'auto',
}}
dangerouslySetInnerHTML={{ __html: content }}
/>
)}
</>
)
}
{
"google-maps-embed": "GoogleMapsEmbed",
"youtube-embed": "YoutubeEmbed"
}
{
"extends": "../../tsconfig-tsec.json",
"compilerOptions": {
"sourceMap": true,
"strict": true,
"esModuleInterop": true,
"target": "es2020",
"lib": ["dom"],
"downlevelIteration": true,
"preserveWatchOutput": true,
"outDir": "dist",
"jsx": "react",
"noFallthroughCasesInSwitch": true,
"skipLibCheck": true,
"moduleResolution": "Node16"
},
"include": ["src/**/*.ts", "src/**/*.tsx"],
"exclude": ["node_modules"]
}
...@@ -36,6 +36,7 @@ importers: ...@@ -36,6 +36,7 @@ importers:
'@next/polyfill-module': workspace:* '@next/polyfill-module': workspace:*
'@next/polyfill-nomodule': workspace:* '@next/polyfill-nomodule': workspace:*
'@next/swc': workspace:* '@next/swc': workspace:*
'@next/third-parties': workspace:*
'@opentelemetry/api': 1.4.1 '@opentelemetry/api': 1.4.1
'@svgr/webpack': 5.5.0 '@svgr/webpack': 5.5.0
'@swc/cli': 0.1.55 '@swc/cli': 0.1.55
...@@ -207,6 +208,7 @@ importers: ...@@ -207,6 +208,7 @@ importers:
'@next/polyfill-module': link:packages/next-polyfill-module '@next/polyfill-module': link:packages/next-polyfill-module
'@next/polyfill-nomodule': link:packages/next-polyfill-nomodule '@next/polyfill-nomodule': link:packages/next-polyfill-nomodule
'@next/swc': link:packages/next-swc '@next/swc': link:packages/next-swc
'@next/third-parties': link:packages/third-parties
'@opentelemetry/api': 1.4.1 '@opentelemetry/api': 1.4.1
'@svgr/webpack': 5.5.0 '@svgr/webpack': 5.5.0
'@swc/cli': 0.1.55_@swc+core@1.3.55 '@swc/cli': 0.1.55_@swc+core@1.3.55
...@@ -1098,6 +1100,21 @@ importers: ...@@ -1098,6 +1100,21 @@ importers:
react-refresh: 0.12.0 react-refresh: 0.12.0
webpack: 5.86.0 webpack: 5.86.0
packages/third-parties:
specifiers:
next: ^13.0.0
outdent: 0.8.0
prettier: 2.5.1
react: ^18.2.0
third-party-capital: 1.0.17
dependencies:
next: 13.4.9_biqbaboplfbrettd7655fr4n2y
react: 18.2.0
third-party-capital: 1.0.17
devDependencies:
outdent: 0.8.0
prettier: 2.5.1
packages: packages:
/@ampproject/remapping/2.1.2: /@ampproject/remapping/2.1.2:
...@@ -6190,6 +6207,10 @@ packages: ...@@ -6190,6 +6207,10 @@ packages:
resolution: {integrity: sha512-XQr74QaLeMiqhStEhLn1im9EOMnkypp7MZOwQhGzqp2Weu5eQJbpPxWxixxlYRKWPOmJjsk6qYfYH9kq43yc2w==} resolution: {integrity: sha512-XQr74QaLeMiqhStEhLn1im9EOMnkypp7MZOwQhGzqp2Weu5eQJbpPxWxixxlYRKWPOmJjsk6qYfYH9kq43yc2w==}
dev: true dev: true
/@next/env/13.4.9:
resolution: {integrity: sha512-vuDRK05BOKfmoBYLNi2cujG2jrYbEod/ubSSyqgmEx9n/W3eZaJQdRNhTfumO+qmq/QTzLurW487n/PM/fHOkw==}
dev: false
/@next/react-refresh-utils/13.4.4_react-refresh@0.12.0: /@next/react-refresh-utils/13.4.4_react-refresh@0.12.0:
resolution: {integrity: sha512-E9LtUbyxSIbkT06is0r6OBT7f2XJVx9xWuZuU0MdHsqn4OPk+D9Qvp2QitnXPXUwCVdu/ZYLiJOO74lnfkWYdw==} resolution: {integrity: sha512-E9LtUbyxSIbkT06is0r6OBT7f2XJVx9xWuZuU0MdHsqn4OPk+D9Qvp2QitnXPXUwCVdu/ZYLiJOO74lnfkWYdw==}
peerDependencies: peerDependencies:
...@@ -6202,6 +6223,87 @@ packages: ...@@ -6202,6 +6223,87 @@ packages:
react-refresh: 0.12.0 react-refresh: 0.12.0
dev: false dev: false
/@next/swc-darwin-arm64/13.4.9:
resolution: {integrity: sha512-TVzGHpZoVBk3iDsTOQA/R6MGmFp0+17SWXMEWd6zG30AfuELmSSMe2SdPqxwXU0gbpWkJL1KgfLzy5ReN0crqQ==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [darwin]
requiresBuild: true
dev: false
optional: true
/@next/swc-darwin-x64/13.4.9:
resolution: {integrity: sha512-aSfF1fhv28N2e7vrDZ6zOQ+IIthocfaxuMWGReB5GDriF0caTqtHttAvzOMgJgXQtQx6XhyaJMozLTSEXeNN+A==}
engines: {node: '>= 10'}
cpu: [x64]
os: [darwin]
requiresBuild: true
dev: false
optional: true
/@next/swc-linux-arm64-gnu/13.4.9:
resolution: {integrity: sha512-JhKoX5ECzYoTVyIy/7KykeO4Z2lVKq7HGQqvAH+Ip9UFn1MOJkOnkPRB7v4nmzqAoY+Je05Aj5wNABR1N18DMg==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
requiresBuild: true
dev: false
optional: true
/@next/swc-linux-arm64-musl/13.4.9:
resolution: {integrity: sha512-OOn6zZBIVkm/4j5gkPdGn4yqQt+gmXaLaSjRSO434WplV8vo2YaBNbSHaTM9wJpZTHVDYyjzuIYVEzy9/5RVZw==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
requiresBuild: true
dev: false
optional: true
/@next/swc-linux-x64-gnu/13.4.9:
resolution: {integrity: sha512-iA+fJXFPpW0SwGmx/pivVU+2t4zQHNOOAr5T378PfxPHY6JtjV6/0s1vlAJUdIHeVpX98CLp9k5VuKgxiRHUpg==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
requiresBuild: true
dev: false
optional: true
/@next/swc-linux-x64-musl/13.4.9:
resolution: {integrity: sha512-rlNf2WUtMM+GAQrZ9gMNdSapkVi3koSW3a+dmBVp42lfugWVvnyzca/xJlN48/7AGx8qu62WyO0ya1ikgOxh6A==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
requiresBuild: true
dev: false
optional: true
/@next/swc-win32-arm64-msvc/13.4.9:
resolution: {integrity: sha512-5T9ybSugXP77nw03vlgKZxD99AFTHaX8eT1ayKYYnGO9nmYhJjRPxcjU5FyYI+TdkQgEpIcH7p/guPLPR0EbKA==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [win32]
requiresBuild: true
dev: false
optional: true
/@next/swc-win32-ia32-msvc/13.4.9:
resolution: {integrity: sha512-ojZTCt1lP2ucgpoiFgrFj07uq4CZsq4crVXpLGgQfoFq00jPKRPgesuGPaz8lg1yLfvafkU3Jd1i8snKwYR3LA==}
engines: {node: '>= 10'}
cpu: [ia32]
os: [win32]
requiresBuild: true
dev: false
optional: true
/@next/swc-win32-x64-msvc/13.4.9:
resolution: {integrity: sha512-QbT03FXRNdpuL+e9pLnu+XajZdm/TtIXVYY4lA9t+9l0fLZbHXDYEKitAqxrOj37o3Vx5ufxiRAniaIebYDCgw==}
engines: {node: '>= 10'}
cpu: [x64]
os: [win32]
requiresBuild: true
dev: false
optional: true
/@nicolo-ribaudo/chokidar-2/2.1.8-no-fsevents.3: /@nicolo-ribaudo/chokidar-2/2.1.8-no-fsevents.3:
resolution: {integrity: sha512-s88O1aVtXftvp5bCPB7WnmXc5IwOZZ7YPuwNPt+GtOOXpPvad1LfbmjYv+qII7zP6RU2QGnqve27dnLycEnyEQ==} resolution: {integrity: sha512-s88O1aVtXftvp5bCPB7WnmXc5IwOZZ7YPuwNPt+GtOOXpPvad1LfbmjYv+qII7zP6RU2QGnqve27dnLycEnyEQ==}
requiresBuild: true requiresBuild: true
...@@ -6921,7 +7023,7 @@ packages: ...@@ -6921,7 +7023,7 @@ packages:
/@swc/helpers/0.4.14: /@swc/helpers/0.4.14:
resolution: {integrity: sha512-4C7nX/dvpzB7za4Ql9K81xK3HPxCpHMgwTZVyf+9JQ6VUbn9jjZVN7/Nkdz/Ugzs2CSjqnL/UPXroiVBVHUWUw==} resolution: {integrity: sha512-4C7nX/dvpzB7za4Ql9K81xK3HPxCpHMgwTZVyf+9JQ6VUbn9jjZVN7/Nkdz/Ugzs2CSjqnL/UPXroiVBVHUWUw==}
dependencies: dependencies:
tslib: 2.4.0 tslib: 2.5.3
dev: true dev: true
/@swc/helpers/0.5.1: /@swc/helpers/0.5.1:
...@@ -18165,6 +18267,49 @@ packages: ...@@ -18165,6 +18267,49 @@ packages:
resolution: {integrity: sha1-yobR/ogoFpsBICCOPchCS524NCw=} resolution: {integrity: sha1-yobR/ogoFpsBICCOPchCS524NCw=}
dev: true dev: true
/next/13.4.9_biqbaboplfbrettd7655fr4n2y:
resolution: {integrity: sha512-vtefFm/BWIi/eWOqf1GsmKG3cjKw1k3LjuefKRcL3iiLl3zWzFdPG3as6xtxrGO6gwTzzaO1ktL4oiHt/uvTjA==}
engines: {node: '>=16.8.0'}
hasBin: true
peerDependencies:
'@opentelemetry/api': ^1.1.0
fibers: '>= 3.1.0'
react: ^18.2.0
react-dom: ^18.2.0
sass: ^1.3.0
peerDependenciesMeta:
'@opentelemetry/api':
optional: true
fibers:
optional: true
sass:
optional: true
dependencies:
'@next/env': 13.4.9
'@swc/helpers': 0.5.1
busboy: 1.6.0
caniuse-lite: 1.0.30001406
postcss: 8.4.14
react: 18.2.0
react-dom: 18.2.0_react@18.2.0
styled-jsx: 5.1.1_react@18.2.0
watchpack: 2.4.0
zod: 3.21.4
optionalDependencies:
'@next/swc-darwin-arm64': 13.4.9
'@next/swc-darwin-x64': 13.4.9
'@next/swc-linux-arm64-gnu': 13.4.9
'@next/swc-linux-arm64-musl': 13.4.9
'@next/swc-linux-x64-gnu': 13.4.9
'@next/swc-linux-x64-musl': 13.4.9
'@next/swc-win32-arm64-msvc': 13.4.9
'@next/swc-win32-ia32-msvc': 13.4.9
'@next/swc-win32-x64-msvc': 13.4.9
transitivePeerDependencies:
- '@babel/core'
- babel-plugin-macros
dev: false
/nice-try/1.0.5: /nice-try/1.0.5:
resolution: {integrity: sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==} resolution: {integrity: sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==}
dev: true dev: true
...@@ -20524,7 +20669,7 @@ packages: ...@@ -20524,7 +20669,7 @@ packages:
resolution: {integrity: sha512-jDUfCPJbKOABhwpUKcqCVbbXiloe/QXMcbJ6Iipf3sDIihEzTqRCeMBfRaOHxhBuTYqtASrI1KJWxzztZU4qUQ==} resolution: {integrity: sha512-jDUfCPJbKOABhwpUKcqCVbbXiloe/QXMcbJ6Iipf3sDIihEzTqRCeMBfRaOHxhBuTYqtASrI1KJWxzztZU4qUQ==}
engines: {node: '>=10.0'} engines: {node: '>=10.0'}
dependencies: dependencies:
postcss: 8.4.14 postcss: 8.4.24
dev: true dev: true
/postcss-safe-parser/6.0.0_postcss@8.4.14: /postcss-safe-parser/6.0.0_postcss@8.4.14:
...@@ -20692,7 +20837,7 @@ packages: ...@@ -20692,7 +20837,7 @@ packages:
engines: {node: ^10 || ^12 || >=14} engines: {node: ^10 || ^12 || >=14}
dependencies: dependencies:
colorette: 1.4.0 colorette: 1.4.0
nanoid: 3.3.4 nanoid: 3.3.6
source-map: 0.6.1 source-map: 0.6.1
dev: true dev: true
...@@ -20717,7 +20862,7 @@ packages: ...@@ -20717,7 +20862,7 @@ packages:
resolution: {integrity: sha512-jBDboWM8qpaqwkMwItqTQTiFikhs/67OYVvblFFTM7MrZjt6yMKd6r2kgXizEbTTljacm4NldIlZnhbjr84QYg==} resolution: {integrity: sha512-jBDboWM8qpaqwkMwItqTQTiFikhs/67OYVvblFFTM7MrZjt6yMKd6r2kgXizEbTTljacm4NldIlZnhbjr84QYg==}
engines: {node: ^10 || ^12 || >=14} engines: {node: ^10 || ^12 || >=14}
dependencies: dependencies:
nanoid: 3.3.4 nanoid: 3.3.6
picocolors: 1.0.0 picocolors: 1.0.0
source-map-js: 1.0.2 source-map-js: 1.0.2
dev: true dev: true
...@@ -20800,6 +20945,12 @@ packages: ...@@ -20800,6 +20945,12 @@ packages:
prettier: 2.8.8 prettier: 2.8.8
dev: true dev: true
/prettier/2.5.1:
resolution: {integrity: sha512-vBZcPRUR5MZJwoyi3ZoyQlc1rXeEck8KgeC9AwwOn+exuxLxq5toTRDTSaVrXHxelDMHy9zlicw8u66yxoSUFg==}
engines: {node: '>=10.13.0'}
hasBin: true
dev: true
/prettier/2.8.8: /prettier/2.8.8:
resolution: {integrity: sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==} resolution: {integrity: sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==}
engines: {node: '>=10.13.0'} engines: {node: '>=10.13.0'}
...@@ -22254,7 +22405,7 @@ packages: ...@@ -22254,7 +22405,7 @@ packages:
peerDependencies: peerDependencies:
rollup: ^2.0.0 rollup: ^2.0.0
dependencies: dependencies:
nanoid: 3.3.4 nanoid: 3.3.6
open: 8.4.0 open: 8.4.0
rollup: 2.35.1 rollup: 2.35.1
source-map: 0.7.4 source-map: 0.7.4
...@@ -22313,7 +22464,7 @@ packages: ...@@ -22313,7 +22464,7 @@ packages:
/rxjs/7.5.7: /rxjs/7.5.7:
resolution: {integrity: sha512-z9MzKh/UcOqB3i20H6rtrlaE/CgjLOvheWK/9ILrbhROGTweAi1BaFsTT9FbwZi5Trr1qNRs+MXkhmR06awzQA==} resolution: {integrity: sha512-z9MzKh/UcOqB3i20H6rtrlaE/CgjLOvheWK/9ILrbhROGTweAi1BaFsTT9FbwZi5Trr1qNRs+MXkhmR06awzQA==}
dependencies: dependencies:
tslib: 2.4.0 tslib: 2.5.3
dev: false dev: false
/sade/1.7.4: /sade/1.7.4:
...@@ -23367,6 +23518,23 @@ packages: ...@@ -23367,6 +23518,23 @@ packages:
postcss-load-plugins: 2.3.0 postcss-load-plugins: 2.3.0
dev: true dev: true
/styled-jsx/5.1.1_react@18.2.0:
resolution: {integrity: sha512-pW7uC1l4mBZ8ugbiZrcIsiIvVx1UmTfw7UkC3Um2tmfUq9Bhk8IiyEIPl6F8agHgjzku6j0xQEZbfA5uSgSaCw==}
engines: {node: '>= 12.0.0'}
peerDependencies:
'@babel/core': '*'
babel-plugin-macros: '*'
react: '>= 16.8.0 || 17.x.x || ^18.0.0-0'
peerDependenciesMeta:
'@babel/core':
optional: true
babel-plugin-macros:
optional: true
dependencies:
client-only: 0.0.1
react: 18.2.0
dev: false
/styled-jsx/5.1.1_uuaxwgga6hqycsez5ok7v2wg4i: /styled-jsx/5.1.1_uuaxwgga6hqycsez5ok7v2wg4i:
resolution: {integrity: sha512-pW7uC1l4mBZ8ugbiZrcIsiIvVx1UmTfw7UkC3Um2tmfUq9Bhk8IiyEIPl6F8agHgjzku6j0xQEZbfA5uSgSaCw==} resolution: {integrity: sha512-pW7uC1l4mBZ8ugbiZrcIsiIvVx1UmTfw7UkC3Um2tmfUq9Bhk8IiyEIPl6F8agHgjzku6j0xQEZbfA5uSgSaCw==}
engines: {node: '>= 12.0.0'} engines: {node: '>= 12.0.0'}
...@@ -23815,6 +23983,10 @@ packages: ...@@ -23815,6 +23983,10 @@ packages:
/text-table/0.2.0: /text-table/0.2.0:
resolution: {integrity: sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==} resolution: {integrity: sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==}
/third-party-capital/1.0.17:
resolution: {integrity: sha512-TOoAmaUg1sYZNErMrsEdEp8BSgtnnJL9nhHwisv3kZ2d1Ze0Cjj4zdv/qgwhVPqMvecTI3ZNxhrKSvkYEY2qtg==}
dev: false
/throat/6.0.1: /throat/6.0.1:
resolution: {integrity: sha512-8hmiGIJMDlwjg7dlJ4yKGLK8EsYqKgPWbG3b4wjJddKNwc7N7Dpn08Df4szr/sZdMVeOstrdYSsqzX6BYbcB+w==} resolution: {integrity: sha512-8hmiGIJMDlwjg7dlJ4yKGLK8EsYqKgPWbG3b4wjJddKNwc7N7Dpn08Df4szr/sZdMVeOstrdYSsqzX6BYbcB+w==}
......
...@@ -8,8 +8,16 @@ export default function Page() { ...@@ -8,8 +8,16 @@ export default function Page() {
<h2>next/script</h2> <h2>next/script</h2>
<Client /> <Client />
<Script strategy="lazyOnload" src="/test4.js" /> <Script strategy="lazyOnload" src="/test4.js" />
<Script strategy="afterInteractive" src="/test3.js" /> <Script
<Script strategy="beforeInteractive" src="/test1.js" /> strategy="afterInteractive"
src="/test3.js"
stylesheets={['/style3.css']}
/>
<Script
strategy="beforeInteractive"
src="/test1.js"
stylesheets={['/style1a.css', '/style1b.css']}
/>
<Script strategy="beforeInteractive" id="1.5">{` <Script strategy="beforeInteractive" id="1.5">{`
;(window._script_order = window._script_order || []).push(1.5) ;(window._script_order = window._script_order || []).push(1.5)
console.log(window._script_order) console.log(window._script_order)
......
...@@ -1839,6 +1839,15 @@ createNextDescribe( ...@@ -1839,6 +1839,15 @@ createNextDescribe(
'<script rel="preload" as="script" src="/test4.js"/>' '<script rel="preload" as="script" src="/test4.js"/>'
) )
}) })
it('should load stylesheets for next/scripts', async () => {
const html = await next.render('/script')
const $ = cheerio.load(html)
expect($('link[href="/style3.css"]').length).toBe(1)
expect($('link[href="/style1a.css"]').length).toBe(1)
expect($('link[href="/style1b.css"]').length).toBe(1)
})
}) })
describe('data fetch with response over 16KB with chunked encoding', () => { describe('data fetch with response over 16KB with chunked encoding', () => {
......
...@@ -13,6 +13,9 @@ const Page = () => { ...@@ -13,6 +13,9 @@ const Page = () => {
id="scriptLazyOnload" id="scriptLazyOnload"
src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js?a=scriptLazyOnload" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js?a=scriptLazyOnload"
strategy="lazyOnload" strategy="lazyOnload"
stylesheets={[
'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css',
]}
></Script> ></Script>
<Script <Script
src="https://example.com/doesntexist" src="https://example.com/doesntexist"
......
...@@ -70,7 +70,7 @@ const runTests = (isDev = false) => { ...@@ -70,7 +70,7 @@ const runTests = (isDev = false) => {
) )
expect(filteredLogs.length).toBe(0) expect(filteredLogs.length).toBe(0)
async function test(id) { async function test(id, css) {
const script = await browser.elementById(id) const script = await browser.elementById(id)
const dataAttr = await script.getAttribute('data-nscript') const dataAttr = await script.getAttribute('data-nscript')
const endScripts = await browser.elementsByCss( const endScripts = await browser.elementsByCss(
...@@ -81,12 +81,20 @@ const runTests = (isDev = false) => { ...@@ -81,12 +81,20 @@ const runTests = (isDev = false) => {
expect(script).toBeDefined() expect(script).toBeDefined()
expect(dataAttr).toBeDefined() expect(dataAttr).toBeDefined()
if (css) {
const cssTag = await browser.elementByCss(`link[href="${css}"]`)
expect(cssTag).toBeDefined()
}
// Script is inserted at the end // Script is inserted at the end
expect(endScripts.length).toBe(1) expect(endScripts.length).toBe(1)
} }
// lazyOnload script in page // lazyOnload script in page
await test('scriptLazyOnload') await test(
'scriptLazyOnload',
'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css'
)
// lazyOnload script in _document // lazyOnload script in _document
await test('documentLazyOnload') await test('documentLazyOnload')
} finally { } finally {
......
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