This example sets up the boilerplate for an AMP First Site. You can see a live version here. The boilerplate includes the following features:
- AMP Extension helpers (
amp-state,amp-script, ...) - AMP Serviceworker integration
- App manifest
- Offline page
Deploy the example using Vercel:
Execute create-next-app with npm or Yarn to bootstrap the example:
npm init next-app --example amp-first amp-first-app
# or
yarn create next-app --example amp-first amp-first-appDownload the example:
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/amp-first
cd amp-firstInstall it and run:
npm install
npm run dev
# or
yarn
yarn devOpen http://localhost:3000 to view it in the browser. The page will reload if you make edits. You will also see AMP validation errors in the console.
Things you need to do after installing the boilerplate:
- Update your app manifest in
public/manifest.jsonwith your app-specific data (theme_color,background_color,name,short_name). - Update the
THEME_COLORvariable defined incomponents/Layout.js. - Update favicon and icons in
public/favicon.icoandpublic/static/images/icons-*.png. - Set the default language in
pages/_document.js. - Review the AMP Serviceworker implementation in
public/serviceworker.js.
-
Using AMP Components: you can import AMP components using
next/head. Checkoutcomponents/amp/AmpCustomElementfor a simple way to import AMP components. Once the component is imported, you can use it like any other HTML element. -
amp-bind & amp-state: it's no problem to use
amp-bindandamp-statewith Next.js. There are two things to be aware of:-
The
[...]binding syntax, e.g.[text]="myStateVariable", is not supported in JSX. Usedata-amp-bind-text="myStateVariable"instead. -
Initializing
amp-statevia JSON string is not supported in JSX:<amp-state id="myState"> <script type="application/json"> { "foo": "bar" } </script> </amp-state>
Instead you need to use
dangerouslySetInnerHTMLto initialize the string. can use the/components/amp/AmpState.jscomponent to see how it works. The same approach works foramp-accessandamp-consentas well:<AmpState id="message" value={ message: 'Hello World' }/>
-
-
amp-list & amp-mustache: mustache templates conflict with JSX and it's template literals need to be escaped. A simple approach is to escape them via back ticks:
src={`{{imageUrl}}`}. -
amp-script: you can use amp-script to add custom JavaScript to your AMP pages. The boilerplate includes a helper
components/amp/AmpScript.jsto simplify using amp-script. The helper also supports embedding inline scripts. Good to know: Next.js uses AMP Optimizer under the hood, which automatically adds the needed script hashes for inline amp-scripts.
For production builds, you need to run (the app will be build into the .next folder):
$ yarn buildTo start the application in production mode, run:
$ yarn startDeploy it to the cloud with Vercel (Documentation).