Unverified Commit bfd96ac0 authored by Max Proske's avatar Max Proske Committed by GitHub

Fix `with-webassembly` example and convert to Typescript (#43677)

- Fixes `with-webassembly` example unable to build with the current
`next.config.js`.
https://github.com/vercel/next.js/issues/29362#issuecomment-932767530
- Converted example to TypeScript

```js
// Before
config.output.webassemblyModuleFilename = 'static/wasm/[modulehash].wasm'

// After
config.output.webassemblyModuleFilename =
  isServer && !dev
    ? '../static/wasm/[modulehash].wasm'
    : 'static/wasm/[modulehash].wasm'
```

```
> Build error occurred
Error: Export encountered errors on following paths:
        /
    at /Users/max/dev/next.js/examples/with-webassembly/node_modules/next/dist/export/index.js:408:19
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Span.traceAsyncFn (/Users/max/dev/next.js/examples/with-webassembly/node_modules/next/dist/trace/trace.js:79:20)
    at async /Users/max/dev/next.js/examples/with-webassembly/node_modules/next/dist/build/index.js:1342:21
    at async Span.traceAsyncFn (/Users/max/dev/next.js/examples/with-webassembly/node_modules/next/dist/trace/trace.js:79:20)
    at async /Users/max/dev/next.js/examples/with-webassembly/node_modules/next/dist/build/index.js:1202:17
    at async Span.traceAsyncFn (/Users/max/dev/next.js/examples/with-webassembly/node_modules/next/dist/trace/trace.js:79:20)
    at async Object.build [as default] (/Users/max/dev/next.js/examples/with-webassembly/node_modules/next/dist/build/index.js:65:29)
 ELIFECYCLE  Command failed with exit code 1.
```

## Documentation / Examples

- [X] Make sure the linting passes by running `pnpm build && pnpm lint`
- [X] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
parent ce0bcd38
...@@ -32,4 +32,6 @@ To compile `src/add.rs` to `add.wasm` run: ...@@ -32,4 +32,6 @@ To compile `src/add.rs` to `add.wasm` run:
npm run build-rust npm run build-rust
# or # or
yarn build-rust yarn build-rust
# or
pnpm build-rust
``` ```
import { withRouter } from 'next/router' import type { AddModuleExports } from '../wasm'
import dynamic from 'next/dynamic' import dynamic from 'next/dynamic'
import Link from 'next/link'
interface RustComponentProps {
number: Number
}
const RustComponent = dynamic({ const RustComponent = dynamic({
loader: async () => { loader: async () => {
// Import the wasm module // Import the wasm module
const rustModule = await import('../add.wasm') // @ts-ignore
const exports = (await import('../add.wasm')) as AddModuleExports
const { add_one: addOne } = exports
// Return a React component that calls the add_one method on the wasm module // Return a React component that calls the add_one method on the wasm module
return (props) => <div>{rustModule.add_one(props.number)}</div> return ({ number }: RustComponentProps) => (
<div>
<>{addOne(number)}</>
</div>
)
}, },
}) })
const Page = ({ router: { query } }) => { export default RustComponent
const number = parseInt(query.number || 30)
return (
<div>
<RustComponent number={number} />
<Link href={`/?number=${number + 1}`}>+</Link>
</div>
)
}
export default withRouter(Page)
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
module.exports = { const nextConfig = {
webpack(config) { webpack(config, { isServer, dev }) {
config.output.webassemblyModuleFilename = 'static/wasm/[modulehash].wasm' // Use the client static directory in the server bundle and prod mode
// Fixes `Error occurred prerendering page "/"`
config.output.webassemblyModuleFilename =
isServer && !dev
? '../static/wasm/[modulehash].wasm'
: 'static/wasm/[modulehash].wasm'
// Since Webpack 5 doesn't enable WebAssembly by default, we should do it manually // Since Webpack 5 doesn't enable WebAssembly by default, we should do it manually
config.experiments = { ...config.experiments, asyncWebAssembly: true } config.experiments = { ...config.experiments, asyncWebAssembly: true }
...@@ -9,3 +14,5 @@ module.exports = { ...@@ -9,3 +14,5 @@ module.exports = {
return config return config
}, },
} }
module.exports = nextConfig
{ {
"private": true, "private": true,
"dependencies": {
"next": "latest",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"scripts": { "scripts": {
"dev": "next", "dev": "next",
"build": "next build", "build": "next build",
"build-rust": "rustc --target wasm32-unknown-unknown -O --crate-type=cdylib src/add.rs -o add.wasm", "build-rust": "rustc --target wasm32-unknown-unknown -O --crate-type=cdylib src/add.rs -o add.wasm",
"start": "next start" "start": "next start"
},
"dependencies": {
"next": "latest",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/node": "^18.11.10",
"@types/react": "^18.0.26",
"@types/react-dom": "^18.0.9",
"typescript": "^4.9.3"
} }
} }
import add_module from '../../add.wasm?module'
const instance$ = WebAssembly.instantiate(add_module)
export default async function edgeExample() {
const { exports } = await instance$
const number = exports.add_one(10)
return new Response(`got: ${number}`)
}
export const config = { runtime: 'experimental-edge' }
import type { AddModuleExports } from '../../wasm'
// @ts-ignore
import addWasm from '../../add.wasm?module'
const module$ = WebAssembly.instantiate(addWasm)
export default async function handler() {
const instance = (await module$) as any
const exports = instance.exports as AddModuleExports
const { add_one: addOne } = exports
const number = addOne(10)
return new Response(`got: ${number}`)
}
export const config = { runtime: 'experimental-edge' }
import { useRouter } from 'next/router'
import Link from 'next/link'
import RustComponent from '../components/RustComponent'
export default function Page() {
const { query } = useRouter()
const number = parseInt(query.number as string) || 30
return (
<div>
<RustComponent number={number} />
<Link href={`/?number=${number + 1}`}>+</Link>
</div>
)
}
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "wasm.d.ts"],
"exclude": ["node_modules"]
}
export interface AddModuleExports {
add_one(number: Number): Number
}
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