polymer README

The project's README from github.com/Polymer/polymer. As one markdown file: README.md.

Polymer

Build Status Published on npm Published on webcomponents.org

ℹ️ Note: This is the current stable version of the Polymer library. At Google I/O 2018 we announced a new Web Component base class, LitElement, as a successor to the PolymerElement base class in this library.

If you're starting a new project, we recommend that you consider using LitElement instead.

If you have a project you've built with an earlier version of the Polymer library, we recommend that you migrate to 3.0 for best compatibility with the JavaScript ecosystem. Thanks to the interoperability of Web Components, elements built with Polymer 3.0 and LitElement can be mixed and matched in the same app, so once you have updated your project to Polymer 3.0, you can migrate to LitElement incrementally, one element at a time. See our blog post on the Polymer Project roadmap for more information.

Polymer lets you build encapsulated, reusable Web Components that work just like standard HTML elements, to use in building web applications. Using a Web Component built with Polymer is as simple as importing its definition then using it like any other HTML element:

<!-- Import a component -->
<script src="https://unpkg.com/@polymer/paper-checkbox@next/paper-checkbox.js?module" type="module" ></script>

<!-- Use it like any other HTML element -->
<paper-checkbox>Web Components!</paper-checkbox>

Web Components are now implemented natively on Safari and Chrome (~70% of installed browsers), and run well on Firefox, Edge, and IE11 using polyfills. Read more below.

Getting started

CodePen.

Minimal Example

  1. Create a class that extends PolymerElement.
  2. Implement a static properties getter that describes the element's public property/attribute API (these automatically become observed attributes).
  3. Then implement a template getter that returns an HTMLTemplateElement describing the element's rendering, including encapsulated styling and any property bindings.
  <script src="node_modules/@webcomponents/webcomponents-loader.js"></script>
  <script type="module">
    import {PolymerElement, html} from '@polymer/polymer';

    class MyElement extends PolymerElement {
      static get properties() { return { mood: String }}
      static get template() {
        return html`
          <style> .mood { color: green; } </style>
          Web Components are <span class="mood">[[mood]]</span>!
        `;
      }
    }

    customElements.define('my-element', MyElement);
  </script>

  <my-element mood="happy"></my-element>

Overview

Web components are an incredibly powerful new set of primitives baked into the web platform, and open up a whole new world of possibility when it comes to componentizing front-end code and easily creating powerful, immersive, app-like experiences on the web.

Polymer is a lightweight library built on top of the web standards-based Web Components APIs, and makes it easier to build your very own custom HTML elements. Creating reusable custom elements - and using elements built by others - can make building complex web applications easier and more efficient.

By being based on the Web Components APIs built in the browser (or polyfilled where needed), elements built with Polymer are:

Among many ways to leverage custom elements, they can be particularly useful for building reusable UI components. Instead of continually re-building a specific navigation bar or button in different frameworks and for different projects, you can define this element once using Polymer, and then reuse it throughout your project or in any future project.

Polymer provides a declarative syntax to easily create your own custom elements, using all standard web technologies - define the structure of the element with HTML, style it with CSS, and add interactions to the element with JavaScript.

Polymer also provides optional two-way data-binding, meaning:

  1. When properties in the model for an element get updated, the element can update itself in response.
  2. When the element is updated internally, the changes can be propagated back to the model.

Polymer is designed to be flexible, lightweight, and close to the web platform - the library doesn't invent complex new abstractions and magic, but uses the best features of the web platform in straightforward ways to simply sugar the creation of custom elements.

About Polymer 3.0

Polymer 3.0 is now released to stable, and introduces a major change to how Polymer is distributed: from HTML Imports on Bower, to JS modules on npm. Otherwise, the API is almost entirely backward compatible with Polymer 2.0 (the only changes are removing APIs related to HTML Imports like importHref, and converting Polymer's API to be module-based rather than globals-based).

Migrating to Polymer 3.0 by hand is mostly mechanical:

However, the polymer-modulizer tool automates the vast majority of this migration work. Please see details on that repo for automated conversion of Polymer 2.0 apps and elements to Polymer 3.0.

👀 Looking for Polymer v2.x? Please see the v2 branch.

👀 Looking for Polymer v1.x? Please see the v1 branch.

Contributing

The Polymer team loves contributions from the community! Take a look at our contributing guide for more information on how to contribute. Please file issues on the Polymer issue tracker following the issue template and contributing guide issues.

Communicating with the Polymer team

Beyond GitHub, we try to have a variety of different lines of communication available:

License

The Polymer library uses a BSD-like license that is available here

polymer (Polymer/polymer)

Searching Database…

Что это такое?Polymer — это изначальная open-source библиотека от Google для создания Web Components — инкапсулированных, переиспользуемых пользовательских HTML-элементов, которые работают в веб-приложениях точно так же, как обычные HTML-теги. В этом репозитории находится текущий стабильный релиз — Polymer 3.0.
Это полноценный фреймворк вроде React или что-то полегче?Это лёгкая библиотека поверх нативных API браузера Web Components, а не полноценный фреймворк — она упрощает создание пользовательских элементов на HTML, CSS и JavaScript, при желании с двусторонней привязкой данных, не придумывая собственных тяжёлых абстракций.
Как мне её попробовать и добавить в проект?Можно сразу попробовать в онлайн-песочницах вроде StackBlitz или Glitch либо установить через npm. Чтобы запустить всё в браузере, нужен инструментарий с поддержкой модулей: Polymer CLI ('polymer serve' для разработки, 'polymer build' для продакшена) или инструменты вроде webpack и Rollup, которые переписывают импорты из npm в URL.
В каких браузерах это реально работает?Web Components нативно работают в Safari и Chrome — это примерно 70% установленных браузеров, — а в Firefox, Edge и IE11 хорошо работают через polyfill-ы. Polymer 3.0 публикуется на npm в виде JavaScript-модулей, так что достаточно нативного загрузчика модулей современного браузера и npm-инструментария.
Стоит ли использовать её для нового проекта прямо сейчас?Для новых проектов — нет: на Google I/O 2018 команда объявила LitElement преемником и рекомендует его для новых разработок. Существующим приложениям стоит сначала обновиться до Polymer 3.0, а затем можно постепенно мигрировать на LitElement — по одному элементу за раз.
Как мне описать свой собственный элемент?Создайте класс, наследующий PolymerElement, добавьте статический геттер properties, описывающий публичный API свойств и атрибутов (свойства автоматически становятся наблюдаемыми атрибутами), и геттер template, возвращающий HTMLTemplateElement с разметкой элемента, инкапсулированными стилями и привязками. Затем зарегистрируйте класс через customElements.define.
Поддерживается ли двусторонняя привязка данных?Да, опционально: когда свойства в модели элемента обновляются, элемент может обновляться в ответ, а изменения внутри элемента могут передаваться обратно в модель.
Можно ли смешивать элементы Polymer с кодом на React, Vue или LitElement?Да. Поскольку они построены на стандартах веб-платформы, элементы Polymer совместимы между фреймворками, а элементы, созданные на Polymer 3.0 и LitElement, можно свободно смешивать в одном приложении — именно поэтому возможна миграция на LitElement по одному элементу за раз.
Что изменилось в Polymer 3.0 по сравнению с 2.x?Поставка переехала с HTML Imports на Bower на JS-модули на npm. API почти полностью обратно совместим — изменения сводятся к удалению importHref и переходу от глобальных объектов к модулям. Миграция в основном механическая, и инструмент polymer-modulizer автоматизирует подавляющую её часть; версии v1.x и v2.x живут в отдельных ветках.
Creator
Polymer
Size
31 MB
Stars
22K
Age
14y
Commits · 90 Days