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

@ulibka68/youtube-player-iframe

v1.0.0

Published

Package to show youtube picture and repalce it to iframe if user want to play it. Each iframe load about 500kb

Downloads

3

Readme

Данный проект основан на проекте Harvey Delaney

alt-текст

Статья в блоге

Репозитарий

React Component Library

В процессе работы были обновлены зависимости и плагины на современные (по состоянию на декабрь 2020):

В проекте также использован:

  • Storybook to help you create and show off your components
  • Emotion 11 для стилизации компонентов

Читайте статью Harvey как это сделано ▸

Использование компонента

Если вставлять видео с youtube обычным iframe - то iframe грузит сам по себе порядка 500кб данных, при этом если нужно несколько видео - то 500кб умножается на количество вставленных видео

Решение - грузить с youtube только обложки видео (при возможности в формате webp) а при нажатии на кнопку вставлять iframe

Самому компоненту нужно передать ID видео например для этого видео https://youtu.be/J71jocEBLq0 его ID=J71jocEBLq0

Разработка

Сборка модуля

npm run build

Storybook

To run a live-reload Storybook server on your local machine:

npm run storybook

To export your Storybook as static files:

npm run storybook:export

You can then serve the files under storybook-static using S3, GitHub pages, Express etc. I've hosted this library at: https://www.harveydelaney.com/react-component-library

Генерация нового компонента

Harvey также включил в проект небольшую NodeJS утилиту в директории util названную create-component.js. Вместо того чтобы копировать предыдущий компонент, Вы можете выполнить эту команду для генерации нового компонента. Для использования наберите:

npm run generate YourComponentName

Эта команда сгенерирует:

/src
  /YourComponentName
    YourComponentName.tsx
    YourComponentName.stories.tsx
    YourComponentName.test.tsx
    YourComponentName.types.ts
    YourComponentName.scss

Шаблоны по умолчанию Вы можете поменять в папке util/templates.

Не забудьте добавить новый компонент в файл index.ts лежащий в корневой директории - иначе Ваш компонент не будет экспортирован!

Установка Component Library локально

Допустим что Вы хотите протестировать свою библиотеку вместе с другим проектом (test-app) на Вашей локальной машине, и Вы хотите установить Ваш новый без предварительной публикации в npm. В папке test-app , запустите:

npm i --save ../react-component-library

Эта команда установит локальный компонент в качестве зависимости для test-app. Компонент также появится в виде зависимости в package.json например:

  ...
  "dependencies": {
    ...
    "react-component-library": "file:../react-component-library",
    ...
  },
  ...

Дальше Вы можете импортировать его как и с обычной библотекой.

Публикация на NPM

Сперва убедитесь что у Вас есть аккаунт NPM также Вы должны залогиниться в NPM используя команду npm login.

Установите поле name в package.json в котором укажите имя Вашего пакета. Далее запустите публикацию:

npm publish

Скрипт "prepublishOnly": "npm run build" в package.json будет выполнен перед публикацией, обеспечивая компиляцию библотеки в директорию build/.

Emotion версии 11

В данный пакет уже включена поддержка Emotion версии 11

Использование

Let's say you created a public NPM package called harvey-component-library with the TestComponent component created in this repository.

Usage of the component (after the library installed as a dependency into another project) will be:

import React from "react";
import { TestComponent } from "harvey-component-library";

const App = () => (
  <div className="app-container">
    <h1>Hello I'm consuming the component library</h1>
    <TestComponent theme="primary" />
  </div>
);

export default App;

Check out this Code Sandbox for a live example.

Using Component Library SASS Variables

I've found that it's helpful to export SASS variables to projects consuming the library. As such, I've added the rollup-plugin-copy NPM package and used it to copy the typography.scss and variables.scss into the build directory as part of the Rollup bundle process. This allows you to use these variables in your projects consuming the component library.

For example, let's say you installed harvey-component-library into your project. To use the exported variables/mixins, in a SASS file you would do the following:

@import '~harvey-component-library/build/typography';

.example-container {
    @include heading;

    color: $harvey-white;
}

Additional Help

Component Code Splitting

Code splitting of your components is not supported by default.

Read this section of my blog post to find out how and why you would enable code splitting of your components. In summary, code splitting enables users to import components in isolation like:

import TestComponent from 'harvey-component-library/build/TestComponent';

This can reduce the bundle size for projects using older (CJS) module formats.

You can check out this branch or this commit to see what changes are neccesary to implement it.

Please note, there's an issue with code splitting and using rollup-plugin-postcss. I recommend using rollup-plugin-sass instead alongside code splitting.

Supporting Image Imports

Add the following library to your component library @rollup/plugin-image:

npm i -D @rollup/plugin-image

Then add it to rollup-config.js:

...
plugins:[
  ...,
  image(),
  ...
]
...

You can then import and render images in your components like:

import logo from "./rollup.png";

export const ImageComponent = () => (
  <div>
    <img src={logo} />
  </div>
);

Supporting JSON Imports

Add the following library to your component library @rollup/plugin-json:

npm i -D @rollup/plugin-json

Then add it to rollup-config.js:

...
plugins:[
  ...,
  json(),
  ...
]
...

You can then import and use JSON as ES6 Modules:

import data from "./some-data.json";

export const JsonDataComponent = () => <div>{data.description}</div>;

Checkout the official Rollup plugin list for additional helpful plugins.