二、Next.js 的 Assets, Metadata, and CSS

原文参考:

静态资源存储 (Assets)

  • 可以在顶级公共目录下提供静态资产,如图像等数据,接下来是如何存储及引用他们,为了接下来的测试做一些准备工作。
  • 创建目录 public/images
  • 找一个大致 400px 乘 400px 左右的 jpg 图片,存进去。
  • 将该文件重新命名为 profile.jpg

Image 组件

  • 相较于直接试用 <img> 标记有如下好处:
1、根据不同屏幕尺寸对图片尺寸进行优化,避免小设备上使用大图的资源浪费。
2、支持Lazy loaded。
  • 修改一下之前添加的 first-post.js
import Link from 'next/link';
import Image from "next/image";

export default function FirstPost() {
  return <>
    <h1>First Post</h1>
    <h1 className="title">
      Back to home <Link href="/">Back!</Link>
    </h1>
    <Image
      src="/images/profile.jpg" // Route of the image file
      height={144} // Desired size with correct aspect ratio
      width={144} // Desired size with correct aspect ratio
      alt="Try image"
    />
  </>;
}
  • 运行后的结果,经过比对可以看出图片是按照 height width 进行了对应的比例压缩。


    image.png

Metadata 组件

  • Head 组件需要通过 next/head 引入进来。
  • 做一个尝试继续修改 first-post.js 文件给这个页面加入 Head
import Link from 'next/link';
import Image from "next/image";
// import Head from "next/document"; 注意HEAD不要从这里引入,如果从这里会报错 `Cannot destructure property 'styles' of 'this.context' as it is null`
import Head from 'next/head';

export default function FirstPost() {
  return <>
    <Head>
      <title>First Post</title>
    </Head>
    <h1>First Post</h1>
    <h1 className="title">
      Back to home <Link href="/">Back!</Link>
    </h1>
    <Image
      src="/images/profile.jpg" // Route of the image file
      height={144} // Desired size with correct aspect ratio
      width={144} // Desired size with correct aspect ratio
      alt="Try image"
    />
  </>;
}
  • 结果:


    image.png

添加第三方JavaScript到页面

  • Next 框架提供了 next/script 来辅助引用外部脚本,当然 script 标签依然可以工作,但是最好通过这个来引入,他可以添加一些策略控制和加载后的事件,体验会更好。
  • 继续修改 first-post.js 文件进行测试:
import Link from 'next/link';
import Image from "next/image";
import Script from 'next/script';
import Head from 'next/head';

export default function FirstPost() {
  return <>
    <Head>
      <title>First Post</title>
    </Head>
    {/*这里是新加入的内容*/}
    <Script
      src="https://connect.facebook.net/en_US/sdk.js"
      strategy="lazyOnload"
      onLoad={() =>
        console.log(`script loaded correctly, window.FB has been populated`)
      }
    />
    {/*新加入内容结束*/}
    <h1>First Post</h1>
    <h1 className="title">
      Back to home <Link href="/">Back!</Link>
    </h1>
    <Image
      src="/images/profile.jpg" // Route of the image file
      height={144} // Desired size with correct aspect ratio
      width={144} // Desired size with correct aspect ratio
      alt="Try image"
    />
  </>;
}

  • 结果,脚本已经加载日志已经成功输出。


    image.png

结束

接下来了解 Next.js 的布局组件

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容