Unverified Commit 79016b87 authored by Houssein Djirdeh's avatar Houssein Djirdeh Committed by GitHub

Adds web worker support to `<Script />` using Partytown (#34244)

## Summary

This PR adds a new `worker` strategy to the `<Script />` component that automatically relocates and executes the script in a web worker.

```jsx
<Script 
  strategy="worker"
  ...
/>
```

[Partytown](https://partytown.builder.io/) is used under the hood to provide this functionality.

## Behavior

- This will land as an experimental feature and will only work behind an opt-in flag in `next.config.js`:

  ```js
  experimental: {
    nextScriptWorkers: true
  }
  ```

- This setup use a similar approach to how ESLint and Typescript is used in Next.js by showing an error to the user to install the dependency locally themselves if they've enabled the experimental `nextScriptWorkers` flag.

  <img width="1068" alt="Screen Shot 2022-03-03 at 2 33 13 PM" src="https://user-images.githubusercontent.com/12476932/156639227-42af5353-a2a6-4126-936e-269112809651.png">
- For Partytown to work, a number of static files must be served directly from the site (see [docs](https://partytown.builder.io/copy-library-files)). In this PR, these files are automatically copied to a `~partytown` directory in `.next/static` during `next build` and `next dev` if the `nextScriptWorkers` flag is set to true.

## Checklist

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

This PR fixes #31517.
parent 3b9864d4
......@@ -25,6 +25,7 @@ packages/next-codemod/**/*.d.ts
packages/next-env/**/*.d.ts
packages/create-next-app/templates/**
test/integration/eslint/**
test/integration/script-loader/**/*
test/development/basic/legacy-decorators/**/*
test/production/emit-decorator-metadata/**/*.js
test-timings.json
......
......@@ -41,6 +41,9 @@ The loading strategy of the script.
| `beforeInteractive` | Load script before the page becomes interactive |
| `afterInteractive` | Load script immediately after the page becomes interactive |
| `lazyOnload` | Load script during browser idle time |
| `worker` | Load script in a web worker |
> **Note: `worker` is an experimental strategy that can only be used when enabled in `next.config.js`. See [Off-loading Scripts To A Web Worker](/docs/basic-features/script#off-loading-scripts-to-a-web-worker-experimental).**
### onLoad
......
......@@ -67,8 +67,9 @@ With `next/script`, you decide when to load your third-party script by using the
There are three different loading strategies that can be used:
- `beforeInteractive`: Load before the page is interactive
- `afterInteractive`: (**default**): Load immediately after the page becomes interactive
- `afterInteractive`: (**default**) Load immediately after the page becomes interactive
- `lazyOnload`: Load during idle time
- `worker`: (experimental) Load in a web worker
#### beforeInteractive
......@@ -123,6 +124,87 @@ Examples of scripts that do not need to load immediately and can be lazy-loaded
- Chat support plugins
- Social media widgets
### Off-loading Scripts To A Web Worker (experimental)
> **Note: The `worker` strategy is not yet stable and can cause unexpected issues in your application. Use with caution.**
Scripts that use the `worker` strategy are relocated and executed in a web worker with [Partytown](https://partytown.builder.io/). This can improve the performance of your site by dedicating the main thread to the rest of your application code.
This strategy is still experimental and can only be used if the `nextScriptWorkers` flag is enabled in `next.config.js`:
```js
module.exports = {
experimental: {
nextScriptWorkers: true,
},
}
```
Then, run `next` (normally `npm run dev` or `yarn dev`) and Next.js will guide you through the installation of the required packages to finish the setup:
```bash
npm run dev
# You'll see instructions like these:
#
# Please install Partytown by running:
#
# npm install @builder.io/partytown
#
# ...
```
Once setup is complete, defining `strategy="worker` will automatically instantiate Partytown in your application and off-load the script to a web worker.
```jsx
<Script src="https://example.com/analytics.js" strategy="worker" />
```
There are a number of trade-offs that need to be considered when loading a third-party script in a web worker. Please see Partytown's [Trade-Offs](https://partytown.builder.io/trade-offs) documentation for more information.
#### Configuration
Although the `worker` strategy does not require any additional configuration to work, Partytown supports the use of a config object to modify some of its settings, including enabling `debug` mode and forwarding events and triggers.
If you would like to add additonal configuration options, you can include it within the `<Head />` component used in a [custom `_document.js`](/docs/advanced-features/custom-document.md):
```jsx
import { Html, Head, Main, NextScript } from 'next/document'
export default function Document() {
return (
<Html>
<Head>
<script
data-partytown-config
dangerouslySetInnerHTML={{
__html: `
partytown = {
lib: "/_next/static/~partytown/",
debug: true
};
`,
}}
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
```
In order to modify Partytown's configuration, the following conditions must be met:
1. The `data-partytown-config` attribute must be used in order to overwrite the default configuration used by Next.js
2. Unless you decide to save Partytown's library files in a separate directory, the `lib: "/_next/static/~partytown/"` property and value must be included in the configuration object in order to let Partytown know where Next.js stores the necessary static files.
> **Note**: If you are using an [asset prefix](/docs/api-reference/next.config.js/cdn-support-with-asset-prefix.md) and would like to modify Partytown's default configuration, you must include it as part of the `lib` path.
Take a look at Partytown's [configuration options](https://partytown.builder.io/configuration) to see the full list of other properties that can be added.
### Inline Scripts
Inline scripts, or scripts not loaded from an external file, are also supported by the Script component. They can be written by placing the JavaScript within curly braces:
......
......@@ -30,6 +30,7 @@ import loadCustomRoutes, {
import { nonNullable } from '../lib/non-nullable'
import { recursiveDelete } from '../lib/recursive-delete'
import { verifyAndLint } from '../lib/verifyAndLint'
import { verifyPartytownSetup } from '../lib/verify-partytown-setup'
import { verifyTypeScriptSetup } from '../lib/verifyTypeScriptSetup'
import {
BUILD_ID_FILE,
......@@ -2112,6 +2113,17 @@ export default async function build(
console.log('')
}
if (Boolean(config.experimental.nextScriptWorkers)) {
await nextBuildSpan
.traceChild('verify-partytown-setup')
.traceAsyncFn(async () => {
await verifyPartytownSetup(
dir,
join(distDir, CLIENT_STATIC_FILES_PATH)
)
})
}
await nextBuildSpan
.traceChild('telemetry-flush')
.traceAsyncFn(() => telemetry.flush())
......
......@@ -1340,6 +1340,9 @@ export default async function getBaseWebpackConfig(
'process.env.__NEXT_OPTIMIZE_CSS': JSON.stringify(
config.experimental.optimizeCss && !dev
),
'process.env.__NEXT_SCRIPT_WORKERS': JSON.stringify(
config.experimental.nextScriptWorkers && !dev
),
'process.env.__NEXT_SCROLL_RESTORATION': JSON.stringify(
config.experimental.scrollRestoration
),
......@@ -1548,6 +1551,7 @@ export default async function getBaseWebpackConfig(
webpack5Config.module!.parser = {
javascript: {
url: 'relative',
commonjsMagicComments: true,
},
}
webpack5Config.module!.generator = {
......@@ -1608,6 +1612,7 @@ export default async function getBaseWebpackConfig(
reactMode: config.experimental.reactMode,
optimizeFonts: config.optimizeFonts,
optimizeCss: config.experimental.optimizeCss,
nextScriptWorkers: config.experimental.nextScriptWorkers,
scrollRestoration: config.experimental.scrollRestoration,
basePath: config.basePath,
pageEnv: config.experimental.pageEnv,
......
......@@ -192,6 +192,7 @@ export function getPageHandler(ctx: ServerlessHandlerCtx) {
defaultLocale,
domainLocales: i18n?.domains,
optimizeCss: process.env.__NEXT_OPTIMIZE_CSS,
nextScriptWorkers: process.env.__NEXT_SCRIPT_WORKERS,
crossOrigin: process.env.__NEXT_CROSS_ORIGIN,
},
options
......
......@@ -8,7 +8,7 @@ const ScriptCache = new Map()
const LoadCache = new Set()
export interface ScriptProps extends ScriptHTMLAttributes<HTMLScriptElement> {
strategy?: 'afterInteractive' | 'lazyOnload' | 'beforeInteractive'
strategy?: 'afterInteractive' | 'lazyOnload' | 'beforeInteractive' | 'worker'
id?: string
onLoad?: (e: any) => void
onError?: (e: any) => void
......@@ -99,6 +99,10 @@ const loadScript = (props: ScriptProps): void => {
el.setAttribute(attr, value)
}
if (strategy === 'worker') {
el.setAttribute('type', 'text/partytown')
}
el.setAttribute('data-nscript', strategy)
document.body.appendChild(el)
......@@ -150,9 +154,9 @@ function Script(props: ScriptProps): JSX.Element | null {
}
}, [props, strategy])
if (strategy === 'beforeInteractive') {
if (strategy === 'beforeInteractive' || strategy === 'worker') {
if (updateScripts) {
scripts.beforeInteractive = (scripts.beforeInteractive || []).concat([
scripts[strategy] = (scripts[strategy] || []).concat([
{
src,
onLoad,
......
......@@ -384,6 +384,7 @@ export default async function exportApp(
runtime: nextConfig.experimental.runtime,
crossOrigin: nextConfig.crossOrigin,
optimizeCss: nextConfig.experimental.optimizeCss,
nextScriptWorkers: nextConfig.experimental.nextScriptWorkers,
optimizeFonts: nextConfig.optimizeFonts,
reactRoot: nextConfig.experimental.reactRoot || false,
}
......
import { promises } from 'fs'
import chalk from 'next/dist/compiled/chalk'
import path from 'path'
import {
hasNecessaryDependencies,
NecessaryDependencies,
} from './has-necessary-dependencies'
import { isYarn } from './is-yarn'
import { fileExists } from './file-exists'
import { FatalError } from './fatal-error'
import { recursiveDelete } from './recursive-delete'
import * as Log from '../build/output/log'
async function missingDependencyError(dir: string) {
throw new FatalError(
chalk.bold.red(
"It looks like you're trying to use Partytown with next/script but do not have the required package(s) installed."
) +
'\n\n' +
chalk.bold(`Please install Partytown by running:`) +
'\n\n' +
`\t${chalk.bold.cyan(
(await isYarn(dir))
? 'yarn add @builder.io/partytown'
: 'npm install @builder.io/partytown'
)}` +
'\n\n' +
chalk.bold(
`If you are not trying to use Partytown, please disable the experimental ${chalk.cyan(
'"nextScriptWorkers"'
)} flag in next.config.js.`
) +
'\n'
)
}
async function copyPartytownStaticFiles(
deps: NecessaryDependencies,
staticDir: string
) {
const partytownLibDir = path.join(staticDir, '~partytown')
const hasPartytownLibDir = await fileExists(partytownLibDir, 'directory')
if (hasPartytownLibDir) {
await recursiveDelete(partytownLibDir)
await promises.rmdir(partytownLibDir)
}
const { copyLibFiles } = await Promise.resolve(
require(path.join(deps.resolved.get('@builder.io/partytown')!, '../utils'))
)
await copyLibFiles(partytownLibDir)
}
export async function verifyPartytownSetup(
dir: string,
targetDir: string
): Promise<void> {
try {
const partytownDeps: NecessaryDependencies = await hasNecessaryDependencies(
dir,
[{ file: '@builder.io/partytown', pkg: '@builder.io/partytown' }]
)
if (partytownDeps.missing?.length > 0) {
await missingDependencyError(dir)
} else {
try {
await copyPartytownStaticFiles(partytownDeps, targetDir)
} catch (err) {
Log.warn(
`Partytown library files could not be copied to the static directory. Please ensure that ${chalk.bold.cyan(
'@builder.io/partytown'
)} is installed as a dependency.`
)
}
}
} catch (err) {
// Don't show a stack trace when there is an error due to missing dependencies
if (err instanceof FatalError) {
console.error(err.message)
process.exit(1)
}
throw err
}
}
......@@ -19,6 +19,7 @@ export { DocumentContext, DocumentInitialProps, DocumentProps }
export type OriginProps = {
nonce?: string
crossOrigin?: string
children?: React.ReactElement
}
type DocumentFiles = {
......@@ -71,10 +72,76 @@ function getPolyfillScripts(context: HtmlProps, props: OriginProps) {
))
}
function getPreNextWorkerScripts(context: HtmlProps, props: OriginProps) {
const { assetPrefix, scriptLoader, crossOrigin, nextScriptWorkers } = context
if (!nextScriptWorkers) return null
try {
let {
partytownSnippet,
} = require(/* webpackIgnore: true */ '@builder.io/partytown/integration'!)
const children = Array.isArray(props.children)
? props.children
: [props.children]
// Check to see if the user has defined their own Partytown configuration
const userDefinedConfig = children.find(
(child: React.ReactElement) =>
child?.props?.dangerouslySetInnerHTML?.__html.length &&
'data-partytown-config' in child.props
)
return (
<>
{!userDefinedConfig && (
<script
data-partytown-config=""
dangerouslySetInnerHTML={{
__html: `
partytown = {
lib: "${assetPrefix}/_next/static/~partytown/"
};
`,
}}
/>
)}
<script
data-partytown=""
dangerouslySetInnerHTML={{
__html: partytownSnippet(),
}}
/>
{(scriptLoader.worker || []).map((file: ScriptProps, index: number) => {
const { strategy, ...scriptProps } = file
return (
<script
{...scriptProps}
type="text/partytown"
key={scriptProps.src || index}
nonce={props.nonce}
data-nscript="worker"
crossOrigin={props.crossOrigin || crossOrigin}
/>
)
})}
</>
)
} catch (err) {
console.warn(
`Warning: Partytown could not be instantiated in your application due to an error. ${err}`
)
return null
}
}
function getPreNextScripts(context: HtmlProps, props: OriginProps) {
const { scriptLoader, disableOptimizedLoading, crossOrigin } = context
return (scriptLoader.beforeInteractive || []).map(
const webWorkerScripts = getPreNextWorkerScripts(context, props)
const beforeInteractiveScripts = (scriptLoader.beforeInteractive || []).map(
(file: ScriptProps, index: number) => {
const { strategy, ...scriptProps } = file
return (
......@@ -89,6 +156,13 @@ function getPreNextScripts(context: HtmlProps, props: OriginProps) {
)
}
)
return (
<>
{webWorkerScripts}
{beforeInteractiveScripts}
</>
)
}
function getDynamicChunks(
......@@ -450,7 +524,9 @@ export class Head extends Component<
])
return
} else if (
['lazyOnload', 'afterInteractive'].includes(child.props.strategy)
['lazyOnload', 'afterInteractive', 'worker'].includes(
child.props.strategy
)
) {
scriptLoaderItems.push(child.props)
return
......
......@@ -155,6 +155,7 @@ export default abstract class Server {
fontManifest?: FontManifest
disableOptimizedLoading?: boolean
optimizeCss: any
nextScriptWorkers: any
locale?: string
locales?: string[]
defaultLocale?: string
......@@ -315,6 +316,7 @@ export default abstract class Server {
? this.getFontManifest()
: undefined,
optimizeCss: this.nextConfig.experimental.optimizeCss,
nextScriptWorkers: this.nextConfig.experimental.nextScriptWorkers,
disableOptimizedLoading: this.nextConfig.experimental.runtime
? true
: this.nextConfig.experimental.disableOptimizedLoading,
......@@ -1338,6 +1340,7 @@ export default abstract class Server {
locales,
defaultLocale,
optimizeCss: this.renderOpts.optimizeCss,
nextScriptWorkers: this.renderOpts.nextScriptWorkers,
distDir: this.distDir,
fontManifest: this.renderOpts.fontManifest,
domainLocales: this.renderOpts.domainLocales,
......
......@@ -86,6 +86,7 @@ export interface ExperimentalConfig {
workerThreads?: boolean
pageEnv?: boolean
optimizeCss?: boolean
nextScriptWorkers?: boolean
scrollRestoration?: boolean
externalDir?: boolean
conformance?: boolean
......@@ -455,6 +456,7 @@ export const defaultConfig: NextConfig = {
workerThreads: false,
pageEnv: false,
optimizeCss: false,
nextScriptWorkers: false,
scrollRestoration: false,
externalDir: false,
reactRoot: Number(process.env.NEXT_PRIVATE_REACT_ROOT) > 0,
......
......@@ -26,6 +26,7 @@ import { fileExists } from '../../lib/file-exists'
import { findPagesDir } from '../../lib/find-pages-dir'
import loadCustomRoutes from '../../lib/load-custom-routes'
import { verifyTypeScriptSetup } from '../../lib/verifyTypeScriptSetup'
import { verifyPartytownSetup } from '../../lib/verify-partytown-setup'
import {
PHASE_DEVELOPMENT_SERVER,
CLIENT_STATIC_FILES_PATH,
......@@ -393,6 +394,13 @@ export default class DevServer extends Server {
await this.startWatcher()
this.setDevReady!()
if (this.nextConfig.experimental.nextScriptWorkers) {
await verifyPartytownSetup(
this.dir,
pathJoin(this.distDir, CLIENT_STATIC_FILES_PATH)
)
}
const telemetry = new Telemetry({ distDir: this.distDir })
telemetry.record(
eventCliSession(this.distDir, this.nextConfig, {
......
......@@ -111,6 +111,9 @@ export default class NextNodeServer extends BaseServer {
if (this.renderOpts.optimizeCss) {
process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true)
}
if (this.renderOpts.nextScriptWorkers) {
process.env.__NEXT_SCRIPT_WORKERS = JSON.stringify(true)
}
if (!this.minimalMode) {
const { ImageOptimizerCache } =
......
......@@ -216,6 +216,7 @@ export type RenderOptsPartial = {
optimizeFonts: boolean
fontManifest?: FontManifest
optimizeCss: any
nextScriptWorkers: any
devOnlyCacheBusterQueryString?: string
resolvedUrl?: string
resolvedAsPath?: string
......@@ -1487,6 +1488,7 @@ export async function renderToHTML(
crossOrigin: renderOpts.crossOrigin,
optimizeCss: renderOpts.optimizeCss,
optimizeFonts: renderOpts.optimizeFonts,
nextScriptWorkers: renderOpts.nextScriptWorkers,
runtime,
}
......
......@@ -24,7 +24,11 @@ export type HtmlProps = {
unstable_runtimeJS?: false
unstable_JsPreload?: false
devOnlyCacheBusterQueryString: string
scriptLoader: { afterInteractive?: string[]; beforeInteractive?: any[] }
scriptLoader: {
afterInteractive?: string[]
beforeInteractive?: any[]
worker?: any[]
}
locale?: string
disableOptimizedLoading?: boolean
styles?: React.ReactElement[] | React.ReactFragment
......@@ -32,6 +36,7 @@ export type HtmlProps = {
crossOrigin?: string
optimizeCss?: boolean
optimizeFonts?: boolean
nextScriptWorkers?: boolean
runtime?: 'edge' | 'nodejs'
}
......
import webdriver from 'next-webdriver'
import { createNext } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import { BrowserInterface } from 'test/lib/browsers/base'
import { waitFor } from 'next-test-utils'
describe('experimental.nextScriptWorkers: false with no Partytown dependency', () => {
let next: NextInstance
beforeAll(async () => {
next = await createNext({
files: {
'pages/index.js': `
import Script from 'next/script'
export default function Page() {
return (
<>
<Script
src="https://cdn.jsdelivr.net/npm/cookieconsent@3/build/cookieconsent.min.js"
strategy="worker"
/>
</>
)
}
`,
},
dependencies: {},
})
})
afterAll(() => next.destroy())
it('Partytown snippet is not injected to head if not enabled in configuration', async () => {
let browser: BrowserInterface
try {
browser = await webdriver(next.appPort, '/')
const snippetScript = await browser.eval(
`document.querySelector('script[data-partytown]')`
)
expect(snippetScript).toEqual(null)
} finally {
if (browser) await browser.close()
}
})
})
describe('experimental.nextScriptWorkers: true with required Partytown dependency', () => {
let next: NextInstance
beforeAll(async () => {
next = await createNext({
nextConfig: {
experimental: {
nextScriptWorkers: true,
},
},
files: {
'pages/index.js': `
import Script from 'next/script'
export default function Page() {
return (
<>
<Script
src="https://cdn.jsdelivr.net/npm/cookieconsent@3/build/cookieconsent.min.js"
strategy="worker"
/>
</>
)
}
`,
},
dependencies: {
'@builder.io/partytown': '0.4.2',
},
})
})
afterAll(() => next.destroy())
it('Partytown snippets are injected to head if enabled in configuration', async () => {
let browser: BrowserInterface
try {
browser = await webdriver(next.appPort, '/')
const snippetScript = await browser.eval(
`document.querySelector('script[data-partytown]').innerHTML`
)
const configScript = await browser.eval(
`document.querySelector('script[data-partytown-config]').innerHTML`
)
expect(snippetScript).not.toEqual(null)
// A default config is included that points to the correct folder that hosts partytown's static files
expect(configScript).not.toEqual(null)
expect(configScript.replace(/(?: *[\n\r])+ */g, '')).toEqual(
'partytown = {lib: "/_next/static/~partytown/"};'
)
} finally {
if (browser) await browser.close()
}
})
it('Worker scripts are modified by Partytown to execute on a worker thread', async () => {
let browser: BrowserInterface
try {
browser = await webdriver(next.appPort, '/')
const predefinedWorkerScripts = await browser.eval(
`document.querySelectorAll('script[type="text/partytown"]').length`
)
expect(predefinedWorkerScripts).toEqual(1)
await waitFor(1000)
// Partytown modifes type to "text/partytown-x" after it has been executed in the web worker
const processedWorkerScripts = await browser.eval(
`document.querySelectorAll('script[type="text/partytown-x"]').length`
)
expect(processedWorkerScripts).toEqual(1)
} finally {
if (browser) await browser.close()
}
})
})
describe('experimental.nextScriptWorkers: true with config override', () => {
let next: NextInstance
beforeAll(async () => {
next = await createNext({
nextConfig: {
experimental: {
nextScriptWorkers: true,
},
},
files: {
'pages/_document.js': `
import Document, { Html, Head, Main, NextScript } from "next/document";
class MyDocument extends Document {
render() {
return (
<Html>
<Head>
<script
data-partytown-config
dangerouslySetInnerHTML={{
__html: \`
partytown = {
lib: "/_next/static/~partytown/",
debug: true
};
\`,
}}
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
`,
'pages/index.js': `
import Script from 'next/script'
export default function Page() {
return (
<>
<Script
src="https://cdn.jsdelivr.net/npm/cookieconsent@3/build/cookieconsent.min.js"
strategy="worker"
/>
</>
)
}
`,
},
dependencies: {
'@builder.io/partytown': '0.4.2',
},
})
})
afterAll(() => next.destroy())
it('Partytown config script is overwritten', async () => {
let browser: BrowserInterface
try {
browser = await webdriver(next.appPort, '/')
const configScript = await browser.eval(
`document.querySelector('script[data-partytown-config]').innerHTML`
)
expect(configScript).not.toEqual(null)
expect(configScript.replace(/(?: *[\n\r])+ */g, '')).toEqual(
'partytown = {lib: "/_next/static/~partytown/",debug: true};'
)
} finally {
if (browser) await browser.close()
}
})
})
module.exports = {
experimental: {
nextScriptWorkers: true,
},
}
import Script from 'next/script'
const Page = () => {
return (
<div class="container">
<div>Home Page</div>
<Script
src="https://cdn.jsdelivr.net/npm/cookieconsent@3/build/cookieconsent.min.js"
strategy="worker"
/>
</div>
)
}
export default Page
module.exports = {
experimental: {
nextScriptWorkers: true,
},
}
{
"name": "partytown",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"@builder.io/partytown": "0.4.2"
}
}
import Script from 'next/script'
const Page = () => {
return (
<div class="container">
<div>Home Page</div>
<Script
src="https://cdn.jsdelivr.net/npm/cookieconsent@3/build/cookieconsent.min.js"
strategy="worker"
/>
</div>
)
}
export default Page
......@@ -12,21 +12,27 @@ import {
import webdriver from 'next-webdriver'
import cheerio from 'cheerio'
let appDir = join(__dirname, '..')
let appDir = join(__dirname, '../base')
let appWithPartytownMissingDir = join(__dirname, '../partytown-missing')
let server
let appPort
describe('Script Loader', () => {
beforeAll(async () => {
await nextBuild(appDir)
const app = nextServer({
dir: appDir,
dev: false,
quiet: true,
})
async function bootApp(dir) {
await nextBuild(dir)
const app = nextServer({
dir,
dev: false,
quiet: true,
})
server = await startApp(app)
appPort = server.address().port
}
server = await startApp(app)
appPort = server.address().port
describe('Next.js Script - Primary Strategies', () => {
beforeAll(async () => {
await bootApp(appDir)
})
afterAll(() => {
stopApp(server)
......@@ -192,4 +198,16 @@ describe('Script Loader', () => {
if (browser) await browser.close()
}
})
it('Error message is shown if Partytown is not installed locally', async () => {
const { stdout, stderr } = await nextBuild(appWithPartytownMissingDir, [], {
stdout: true,
stderr: true,
})
const output = stdout + stderr
expect(output.replace(/\n|\r/g, '')).toContain(
`It looks like you're trying to use Partytown with next/script but do not have the required package(s) installed.Please install Partytown by running: npm install @builder.io/partytownIf you are not trying to use Partytown, please disable the experimental "nextScriptWorkers" flag in next.config.js.`
)
})
})
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