How to add a view mode for entity type?
View modes are configuration entities.

Like anything else that is a config entity, it's very simply to put into "code": Make it default configuration. Create it in the UI, do a configuration export (admin/config/development/configuration/single/export), and then place core.entity_view_mode.$entity_type.$view_mode.yml file into config/install inside your module.

The view mode will then automatically be imported and created when the module is installed.

Note that it's not hardcoded then, so a user could remove it. If you want to prevent that, you can implement hook_entity_view_mode_access() to deny delete access to your entity for everyone.

By default, you will have a problem re-installing the module because it will not remove that view mode when you uninstall the module and display an error when you install it again. There are two ways to fix that:


Move the config to config/optional instead of config/install. Then it will only be created if it doesn't exist yet.
Add an enforced dependency on your module, which will ensure that it will be removed when the module is uninstalled. Note that this only works if you had this in place when you installed the module the first time.


Like this:

  dependencies:
    enforced:
      module:
        - yourmodule