npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-puppeteer

v1.0.7

Published

截图React组件

Downloads

747

Readme

React-Puppeteer

这是一个可以在tsx环境中,使用puppeteer对tsx组件进行截图的库

强大的现代化框架React.js将为你管理组件和代码

点击 学习 React.js

VScode 安装插件 ES7+ React/Redux/React-Native snippets

环境准备

npm init -y
npm install [email protected] -g
yarn add typescript -D
yarn add react-puppeteer -W
  • .puppeteerrc.cjs

自动搜索浏览器内核

/**
 * @type {import("puppeteer").Configuration}
 */
module.exports = require('react-puppeteer/.puppeteerrc')
  • tsconfig.json
{
  "include": ["src/**/*"],
  // 继承react-puppeteer的ts配置
  "extends": ["react-puppeteer/config/tsconfig.json"]
}
  • src/react-puppeteer.env.d.ts
/// <reference types="react-puppeteer/env" />

使用教程

// src/Word.tsx
import React from 'react'
export default () => {
  return <div> hello React ! </div>
}
// src/image.tsx
import React from 'react'
import { pictureRender, render } from 'react-puppeteer'
import Word from './Word.tsx'
export const pictureRender = (uid: number, Props: Parameters<typeof Word>[0]) => {
    // 生成 html 地址 或 html字符串
    return render({
        // html/hello/uid.html
        join_dir: 'hello',
        html_name: `${uid}.html`,
        html_body: <Word {...Props} />
    })
}
// src/index.ts
import { pictureRender } from './image.tsx'
const img: Buffer | false = await pictureRender(123456, {})
if (img) {
  // 可fs保存到本地
}
  • run
npx tsx src/index.ts

本地调试

  • tsconfig.json
{
  "include": ["routes.server.ts", "routes.config.tsx"]
}
  • routes.server.ts
import { createServer } from 'react-puppeteer'
await createServer()
  • routes.config.tsx
import React from 'react'
import { defineConfig } from 'react-puppeteer'
const Music = () => {
  return <div> 我的音乐</div>
}
export default defineConfig([
  {
    url: '/music',
    options: {
      html_body: <Music />
    }
  }
])
  • dev
npx tsx watch --clear-screen=false src/index.ts

扩展功能

VScode 安装插件 Path Intellisense

文件引入

createRequire 请确保引入的是项目目录下的文件

import React from "react";
import { BackgroundImage, createRequire} from 'react-puppeteer'
const require = createRequire(import.meta.url)
export default function Word() {
  return (
    <>
      <BackgroundImage url={require("./resources/example.png")} size="100% 100%">
       我有了一个背景图
      </BackgroundImage>
      <img src={require("./resources/example.svg")} />
      <img src={require("./resources/example.png")} />
    </>
  );
}

截图方块

Puppeteer 截图是默认body

你可以指定截图的元素为section

也可以设置section为指定的高度

export default function Word({ data }: PropsType) {
  return (
    <div className="text-red-500 p-2 text-xl m-80">Hello, {data.name}!
      <section className="h-[80rem] w-[90rem]">
        嘎嘎
      </section>
    </div>
  )
}
export const pictureRender = (
  uid: number,
  Props: Parameters<typeof Word>[0]
) => {
  // 生成 html 地址 或 html字符串
  return render(
    {
      // html/hello/uid.html
      join_dir: 'hello',
      html_name: `${uid}.html`,
      html_body: <Word {...Props} />
    },
    {
      tab: 'section'
    }
  )
}

元素插入

import { createRequire } from 'react-puppeteer'
const require = createRequire(import.meta.url)
export const Link = () => {
  return (
    <>
      <script src={require('../../resources/js/hello.js')} />
      <link rel="stylesheet" href={require('../../resources/css/hello.css')} />
    </>
  )
}
import { readFileSync } from "fs";
import { render } from 'react-puppeteer';
import { Link } from "./link.tsx";
export const pictureRender = (
  uid: number,
  Props: Parameters<typeof Word>[0]
) => {
  // 生成 html 地址 或 html字符串
  return render(
    {
        // html/hello/uid.html
        join_dir: 'hello',
        html_name: `${uid}.html`,
        html_head: <Link />,
        html_body: <Word {...Props} />
    }
  )
}

引用别名

定义一个显示图片的组件

import React from 'react'
export default () => <div className="show-image"></div>

创建一个css文件

图片位置./resources/exp.png

.show-image {
    // 引入上级目录的图片资源
    background-image: url("../exp.png");
}

正常情况下,截图工具是无法识别css内部引用的其他资源的

  • 资源的位置随便可能会因为插件位置的改变而改变

  • 框架的设计变更也可能发生改变

  • 生产的html文件随时会变化

此时,开发者需要借助别名系统,确保资源能正常被识别出来

import { dirname, join } from 'path'
import { createRequire, render } from 'react-puppeteer'
import ImageComponent from './views/image.tsx'
const require = createRequire(import.meta.url)
export const ScreenshotOptions = {
  // 携带了别名的资源 效果等同 <head />
  html_files: [require('./resources/css/example.main.css')],
  // 设置别名
  file_paths: {
    // 定位自身的 md文件,并获取目录地址
    '@example': dirname(require('./README.md'))
  },
  // <head />
  html_head: <Link />
}
export const pictureRender = (
  uid: number,
  Props: Parameters<typeof ImageComponent>[0]
) => {
  // 生成 html 地址 或 html字符串
  return render({
    // html/hello/uid.html
    join_dir: 'hello',
    html_name: `${uid}.html`,
    ...ScreenshotOptions,
    html_body: <ImageComponent {...Props} />
  })
}
.show-image {
    // 在外部资源中使用别名引用
    background-image: url("@example/resources/exp.png");
}

编译tsx

  • 安装打包环境
yarn add rollup -D
yarn add @rollup/plugin-typescript -D
  • rollup.config.js
import { defineConfig } from 'rollup'
import typescript from '@rollup/plugin-typescript'
export default defineConfig([
  {
    // src 目录
    input: './src/index.ts',
    output: {
      // lib 目录
      dir: 'lib',
      format: 'es',
      sourcemap: false,
      // 保持结构
      preserveModules: true
    },
    plugins: [
      typescript({
        compilerOptions: {
          declaration: false
        },
        include: ['src/**/*']
      })
    ],
    onwarn: (warning, warn) => {
      // 忽略与无法解析the导入相关the警告信息
      if (warning.code === 'UNRESOLVED_IMPORT') return
      // 继续使用默认the警告处理
      warn(warning)
    }
  }
])
nxp rollup --config rollup.config.js

tailwindcss

可以跟talwindcss结合,生产css后,引入到head组件

yarn add tailwind -W
  • input.css
@tailwind base;
@tailwind components;
@tailwind utilities;
  • tailwind.config.js
import { createRequire } from 'module'
const require = createRequire(import.meta.url)
/**
 * @type {import('tailwindcss').Config}
 */
export default {
  // 内容
  content: ['src/**/*.{jsx.tsx.html}'],
  plugins: []
}
  • output

npx 本地 -i 输入 -o 输出 -m 压缩

npx tailwindcss -i ./input.css -o ./output.css -m
  • link.tsx
import React from 'react'
import { createRequire } from 'react-puppeteer'
const require = createRequire(import.meta.url)
export const Link = () => {
  return (
    <>
      <link rel="stylesheet" href={require('./output.css')} />
    </>
  )
}