Kevon  Krajcik

Kevon Krajcik

1656986400

Vite Rollup Plugins: Compatibility List for Official Rollup Plugins

@rollup/plugin-alias

🍣 A Rollup plugin for defining aliases when bundling packages.

Alias 101

Suppose we have the following import defined in a hypothetical file:

import batman from '../../../batman';

This probably doesn't look too bad on its own. But consider that may not be the only instance in your codebase, and that after a refactor this might be incorrect. With this plugin in place, you can alias ../../../batman with batman for readability and maintainability. In the case of a refactor, only the alias would need to be changed, rather than navigating through the codebase and changing all imports.

import batman from 'batman';

If this seems familiar to Webpack users, it should. This is plugin mimics the resolve.extensions and resolve.alias functionality in Webpack.

This plugin will work for any file type that Rollup natively supports, or those which are supported by third-party plugins.

Requirements

This plugin requires an LTS Node version (v8.0.0+) and Rollup v1.20.0+.

Install

Using npm:

npm install @rollup/plugin-alias --save-dev
# or
yarn add -D @rollup/plugin-alias

Usage

Create a rollup.config.js configuration file and import the plugin:

import alias from '@rollup/plugin-alias';

module.exports = {
  input: 'src/index.js',
  output: {
    dir: 'output',
    format: 'cjs'
  },
  plugins: [
    alias({
      entries: [
        { find: 'utils', replacement: '../../../utils' },
        { find: 'batman-1.0.0', replacement: './joker-1.5.0' }
      ]
    })
  ]
};

Then call rollup either via the CLI or the API. If the build produces any errors, the plugin will write a 'alias' character to stderr, which should be audible on most systems.

Options

customResolver

Type: Function | Object
Default: null

Instructs the plugin to use an alternative resolving algorithm, rather than the Rollup's resolver. Please refer to the Rollup documentation for more information about the resolveId hook. For a detailed example, see: Custom Resolvers.

entries

Type: Object | Array[...Object]
Default: null

Specifies an Object, or an Array of Object, which defines aliases used to replace values in import or require statements. With either format, the order of the entries is important, in that the first defined rules are applied first. This option also supports Regular Expression Alias matching.

Note: Entry targets (the object key in the Object Format, or the find property value in the Array Format below) should not end with a trailing slash in most cases. If strange behavior is observed, double check the entries being passed in options.

Object Format

The Object format allows specifying aliases as a key, and the corresponding value as the actual import value. For example:

alias({
  entries: {
    utils: '../../../utils',
    'batman-1.0.0': './joker-1.5.0'
  }
});

Array[...Object] Format

The Array[...Object] format allows specifying aliases as objects, which can be useful for complex key/value pairs.

entries: [
  { find: 'utils', replacement: '../../../utils' },
  { find: 'batman-1.0.0', replacement: './joker-1.5.0' }
];

Regular Expression Aliases

Regular Expressions can be used to search in a more distinct and complex manner. e.g. To perform partial replacements via sub-pattern matching.

To remove something in front of an import and append an extension, use a pattern such as:

{ find:/^i18n\!(.*)/, replacement: '$1.js' }

This would be useful for loaders, and files that were previously transpiled via the AMD module, to properly handle them in rollup as internals.

To replace extensions with another, a pattern like the following might be used:

{ find:/^(.*)\.js$/, replacement: '$1.alias' }

This would replace the file extension for all imports ending with .js to .alias.

Resolving algorithm

This plugin uses resolver plugins specified for Rollup and eventually Rollup default algorithm. If you rely on Node specific features, you probably want @rollup/plugin-node-resolve in your setup.

Custom Resolvers

The customResolver option can be leveraged to provide separate module resolution for an individual alias.

Example:

// rollup.config.js
import alias from '@rollup/plugin-alias';
import resolve from '@rollup/plugin-node-resolve';

const customResolver = resolve({
  extensions: ['.mjs', '.js', '.jsx', '.json', '.sass', '.scss']
});
const projectRootDir = path.resolve(__dirname);

export default {
  // ...
  plugins: [
    alias({
      entries: [
        {
          find: 'src',
          replacement: path.resolve(projectRootDir, 'src')
          // OR place `customResolver` here. See explanation below.
        }
      ],
      customResolver
    }),
    resolve()
  ]
};

 

In the example above the alias src is used, which uses the node-resolve algorithm for files aliased with src, by passing the customResolver option. The resolve() plugin is kept separate in the plugins list for other files which are not aliased with src. The customResolver option can be passed inside each entries item for granular control over resolving allowing each alias a preferred resolver.

Meta

CONTRIBUTING

LICENSE (MIT)


Author: rollup
Source Code: https://github.com/rollup/plugins/
License: 

#vite #Rollup #typescript #javascript

What is GEEK

Buddha Community

Vite Rollup Plugins: Compatibility List for Official Rollup Plugins
Kevon  Krajcik

Kevon Krajcik

1656986400

Vite Rollup Plugins: Compatibility List for Official Rollup Plugins

@rollup/plugin-alias

🍣 A Rollup plugin for defining aliases when bundling packages.

Alias 101

Suppose we have the following import defined in a hypothetical file:

import batman from '../../../batman';

This probably doesn't look too bad on its own. But consider that may not be the only instance in your codebase, and that after a refactor this might be incorrect. With this plugin in place, you can alias ../../../batman with batman for readability and maintainability. In the case of a refactor, only the alias would need to be changed, rather than navigating through the codebase and changing all imports.

import batman from 'batman';

If this seems familiar to Webpack users, it should. This is plugin mimics the resolve.extensions and resolve.alias functionality in Webpack.

This plugin will work for any file type that Rollup natively supports, or those which are supported by third-party plugins.

Requirements

This plugin requires an LTS Node version (v8.0.0+) and Rollup v1.20.0+.

Install

Using npm:

npm install @rollup/plugin-alias --save-dev
# or
yarn add -D @rollup/plugin-alias

Usage

Create a rollup.config.js configuration file and import the plugin:

import alias from '@rollup/plugin-alias';

module.exports = {
  input: 'src/index.js',
  output: {
    dir: 'output',
    format: 'cjs'
  },
  plugins: [
    alias({
      entries: [
        { find: 'utils', replacement: '../../../utils' },
        { find: 'batman-1.0.0', replacement: './joker-1.5.0' }
      ]
    })
  ]
};

Then call rollup either via the CLI or the API. If the build produces any errors, the plugin will write a 'alias' character to stderr, which should be audible on most systems.

Options

customResolver

Type: Function | Object
Default: null

Instructs the plugin to use an alternative resolving algorithm, rather than the Rollup's resolver. Please refer to the Rollup documentation for more information about the resolveId hook. For a detailed example, see: Custom Resolvers.

entries

Type: Object | Array[...Object]
Default: null

Specifies an Object, or an Array of Object, which defines aliases used to replace values in import or require statements. With either format, the order of the entries is important, in that the first defined rules are applied first. This option also supports Regular Expression Alias matching.

Note: Entry targets (the object key in the Object Format, or the find property value in the Array Format below) should not end with a trailing slash in most cases. If strange behavior is observed, double check the entries being passed in options.

Object Format

The Object format allows specifying aliases as a key, and the corresponding value as the actual import value. For example:

alias({
  entries: {
    utils: '../../../utils',
    'batman-1.0.0': './joker-1.5.0'
  }
});

Array[...Object] Format

The Array[...Object] format allows specifying aliases as objects, which can be useful for complex key/value pairs.

entries: [
  { find: 'utils', replacement: '../../../utils' },
  { find: 'batman-1.0.0', replacement: './joker-1.5.0' }
];

Regular Expression Aliases

Regular Expressions can be used to search in a more distinct and complex manner. e.g. To perform partial replacements via sub-pattern matching.

To remove something in front of an import and append an extension, use a pattern such as:

{ find:/^i18n\!(.*)/, replacement: '$1.js' }

This would be useful for loaders, and files that were previously transpiled via the AMD module, to properly handle them in rollup as internals.

To replace extensions with another, a pattern like the following might be used:

{ find:/^(.*)\.js$/, replacement: '$1.alias' }

This would replace the file extension for all imports ending with .js to .alias.

Resolving algorithm

This plugin uses resolver plugins specified for Rollup and eventually Rollup default algorithm. If you rely on Node specific features, you probably want @rollup/plugin-node-resolve in your setup.

Custom Resolvers

The customResolver option can be leveraged to provide separate module resolution for an individual alias.

Example:

// rollup.config.js
import alias from '@rollup/plugin-alias';
import resolve from '@rollup/plugin-node-resolve';

const customResolver = resolve({
  extensions: ['.mjs', '.js', '.jsx', '.json', '.sass', '.scss']
});
const projectRootDir = path.resolve(__dirname);

export default {
  // ...
  plugins: [
    alias({
      entries: [
        {
          find: 'src',
          replacement: path.resolve(projectRootDir, 'src')
          // OR place `customResolver` here. See explanation below.
        }
      ],
      customResolver
    }),
    resolve()
  ]
};

 

In the example above the alias src is used, which uses the node-resolve algorithm for files aliased with src, by passing the customResolver option. The resolve() plugin is kept separate in the plugins list for other files which are not aliased with src. The customResolver option can be passed inside each entries item for granular control over resolving allowing each alias a preferred resolver.

Meta

CONTRIBUTING

LICENSE (MIT)


Author: rollup
Source Code: https://github.com/rollup/plugins/
License: 

#vite #Rollup #typescript #javascript

HI Python

HI Python

1640973720

Beyonic API Python Example Using Flask, Django, FastAPI

Beyonic API Python Examples.

The beyonic APIs Docs Reference: https://apidocs.beyonic.com/

Discuss Beyonic API on slack

The Beyonic API is a representational state transfer, REST based application programming interface that lets you extend the Beyonic dashboard features into your application and systems, allowing you to build amazing payment experiences.

With the Beyonic API you can:

  • Receive and send money and prepaid airtime.
  • List currencies and networks supported by the Beyonic API.
  • Check whether a bank is supported by the Beyonic API.
  • View your account transactions history.
  • Add, retrieve, list, and update contacts to your Beyonic account.
  • Use webhooks to send notifications to URLs on your server that when specific events occur in your Beyonic account (e.g. payments).

Getting Help

For usage, general questions, and discussions the best place to go to is Beyhive Slack Community, also feel free to clone and edit this repository to meet your project, application or system requirements.

To start using the Beyonic Python API, you need to start by downloading the Beyonic API official Python client library and setting your secret key.

Install the Beyonic API Python Official client library

>>> pip install beyonic

Setting your secrete key.

To set the secrete key install the python-dotenv modeule, Python-dotenv is a Python module that allows you to specify environment variables in traditional UNIX-like “.env” (dot-env) file within your Python project directory, it helps us work with SECRETS and KEYS without exposing them to the outside world, and keep them safe during development too.

Installing python-dotenv modeule

>>> pip install python-dotenv

Creating a .env file to keep our secrete keys.

>>> touch .env

Inside your .env file specify the Beyonic API Token .

.env file

BEYONIC_ACCESS_KEY = "enter your API "

You will get your API Token by clicking your user name on the bottom left of the left sidebar menu in the Beyonic web portal and selecting ‘Manage my account’ from the dropdown menu. The API Token is shown at the very bottom of the page.

getExamples.py

import os 
import beyonic
from dotenv import load_dotenv 

load_dotenv()

myapi = os.environ['BEYONIC_ACCESS_KEY']

beyonic.api_key = myapi 

# Listing account: Working. 
accounts = beyonic.Account.list() 
print(accounts)


#Listing currencies: Not working yet.
'''
supported_currencies = beyonic.Currency.list()
print(supported_currencies)

Supported currencies are: USD, UGX, KES, BXC, GHS, TZS, RWF, ZMW, MWK, BIF, EUR, XAF, GNF, XOF, XOF
'''

#Listing networks: Not working yet.
"""
networks = beyonic.Network.list()
print(networks)
"""

#Listing transactions: Working. 
transactions = beyonic.Transaction.list()
print(transactions) 

#Listing contact: Working. 
mycontacts = beyonic.Contact.list() 
print(mycontacts) 


#Listing events: Not working yet.
'''
events = beyonic.Event.list()
print(events)

Error: AttributeError: module 'beyonic' has no attribute 'Event'
'''

Docker file

FROM python:3.8-slim-buster

COPY . .

COPY ./requirements.txt ./requirements.txt

WORKDIR .

RUN pip install -r requirements.txt

CMD [ "python3", "getExamples.py" ]

Build docker image called demo

>>> docker build -t bey .

Run docker image called demo

>>>docker run -t -i bey 

Now, I’ll create a Docker compose file to run a Docker container using the Docker image we just created.


version: "3.6"
services:
  app:
    build: .
    command: python getExamples.py
    volumes:
      - .:/pythonBeyonicExamples

Now we are going to run the following command from the same directory where the docker-compose.yml file is located. The docker compose up command will start and run the entire app.


docker compose up

Output

NB: The screenshot below might differ according to your account deatils and your transcations in deatils.

docker compose up preview

To stop the container running on daemon mode use the below command.

docker compose stop

Output

docker compose preview

Contributing to this repository. All contributions, bug reports, bug fixes, enhancements, and ideas are welcome, You can get in touch with me on twitter @HarunMbaabu.

Download Details:
Author: HarunMbaabu
Source Code: https://github.com/HarunMbaabu/BeyonicAPI-Python-Examples
License: 

#api #python #flask #django #fastapi 

How To Customize WordPress Plugins? (4 Easy Ways To Do)

This is image title
WordPress needs no introduction. It has been in the world for quite a long time. And up till now, it has given a tough fight to leading web development technology. The main reason behind its remarkable success is, it is highly customizable and also SEO-friendly. Other benefits include open-source technology, security, user-friendliness, and the thousands of free plugins it offers.

Talking of WordPress plugins, are a piece of software that enables you to add more features to the website. They are easy to integrate into your website and don’t hamper the performance of the site. WordPress, as a leading technology, has to offer many out-of-the-box plugins.

However, not always the WordPress would be able to meet your all needs. Hence you have to customize the WordPress plugin to provide you the functionality you wished. WordPress Plugins are easy to install and customize. You don’t have to build the solution from scratch and that’s one of the reasons why small and medium-sized businesses love it. It doesn’t need a hefty investment or the hiring of an in-house development team. You can use the core functionality of the plugin and expand it as your like.

In this blog, we would be talking in-depth about plugins and how to customize WordPress plugins to improve the functionality of your web applications.

What Is The Working Of The WordPress Plugins?

Developing your own plugin requires you to have some knowledge of the way they work. It ensures the better functioning of the customized plugins and avoids any mistakes that can hamper the experience on your site.

1. Hooks

Plugins operate primarily using hooks. As a hook attaches you to something, the same way a feature or functionality is hooked to your website. The piece of code interacts with the other components present on the website. There are two types of hooks: a. Action and b. Filter.

A. Action

If you want something to happen at a particular time, you need to use a WordPress “action” hook. With actions, you can add, change and improve the functionality of your plugin. It allows you to attach a new action that can be triggered by your users on the website.

There are several predefined actions available on WordPress, custom WordPress plugin development also allows you to develop your own action. This way you can make your plugin function as your want. It also allows you to set values for which the hook function. The add_ action function will then connect that function to a specific action.

B. Filters

They are the type of hooks that are accepted to a single variable or a series of variables. It sends them back after they have modified it. It allows you to change the content displayed to the user.

You can add the filter on your website with the apply_filter function, then you can define the filter under the function. To add a filter hook on the website, you have to add the $tag (the filter name) and $value (the filtered value or variable), this allows the hook to work. Also, you can add extra function values under $var.

Once you have made your filter, you can execute it with the add_filter function. This will activate your filter and would work when a specific function is triggered. You can also manipulate the variable and return it.

2. Shortcodes

Shortcodes are a good way to create and display the custom functionality of your website to visitors. They are client-side bits of code. They can be placed in the posts and pages like in the menu and widgets, etc.

There are many plugins that use shortcodes. By creating your very own shortcode, you too can customize the WordPress plugin. You can create your own shortcode with the add_shortcode function. The name of the shortcode that you use would be the first variable and the second variable would be the output of it when it is triggered. The output can be – attributes, content, and name.

3. Widgets

Other than the hooks and shortcodes, you can use the widgets to add functionality to the site. WordPress Widgets are a good way to create a widget by extending the WP_Widget class. They render a user-friendly experience, as they have an object-oriented design approach and the functions and values are stored in a single entity.

How To Customize WordPress Plugins?

There are various methods to customize the WordPress plugins. Depending on your need, and the degree of customization you wish to make in the plugin, choose the right option for you. Also, don’t forget to keep in mind that it requires a little bit of technical knowledge too. So find an expert WordPress plugin development company in case you lack the knowledge to do it by yourself.

1. Hire A Plugin Developer3
This is image title

One of the best ways to customize a WordPress plugin is by hiring a plugin developer. There are many plugin developers listed in the WordPress directory. You can contact them and collaborate with world-class WordPress developers. It is quite easy to find a WordPress plugin developer.

Since it is not much work and doesn’t pay well or for the long term a lot of developers would be unwilling to collaborate but, you will eventually find people.

2. Creating A Supporting Plugin

If you are looking for added functionality in an already existing plugin go for this option. It is a cheap way to meet your needs and creating a supporting plugin takes very little time as it has very limited needs. Furthermore, you can extend a plugin to a current feature set without altering its base code.

However, to do so, you have to hire a WordPress developer as it also requires some technical knowledge.

3. Use Custom Hooks

Use the WordPress hooks to integrate some other feature into an existing plugin. You can add an action or a filter as per your need and improve the functionality of the website.

If the plugin you want to customize has the hook, you don’t have to do much to customize it. You can write your own plugin that works with these hooks. This way you don’t have to build a WordPress plugin right from scratch. If the hook is not present in the plugin code, you can contact a WordPress developer or write the code yourself. It may take some time, but it works.

Once the hook is added, you just have to manually patch each one upon the release of the new plugin update.

4. Override Callbacks

The last way to customize WordPress plugins is by override callbacks. You can alter the core functionality of the WordPress plugin with this method. You can completely change the way it functions with your website. It is a way to completely transform the plugin. By adding your own custom callbacks, you can create the exact functionality you desire.

We suggest you go for a web developer proficient in WordPress as this requires a good amount of technical knowledge and the working of a plugin.

Read More

#customize wordpress plugins #how to customize plugins in wordpress #how to customize wordpress plugins #how to edit plugins in wordpress #how to edit wordpress plugins #wordpress plugin customization

Kevon  Krajcik

Kevon Krajcik

1657040400

Rollup Plugin Buble: Compile ES2015 with Buble in Vite

@rollup/plugin-buble

🍣 A Rollup plugin which converts ES2015+ code with the Bublé compiler.

Requirements

This plugin requires an LTS Node version (v8.0.0+) and Rollup v1.20.0+.

Install

Using npm:

npm install @rollup/plugin-buble --save-dev

Usage

Create a rollup.config.js configuration file and import the plugin:

import buble from '@rollup/plugin-buble';

export default {
  input: 'src/index.js',
  output: {
    dir: 'output',
    format: 'cjs'
  },
  plugins: [buble()]
};

Then call rollup either via the CLI or the API.

Options

transforms

Type: Object
Default: { modules: false }

Specifies additional transform options for the Bublé compiler.

exclude

Type: String | Array[...String]
Default: null

A minimatch pattern, or array of patterns, which specifies the files in the build the plugin should ignore. By default no files are ignored.

include

Type: String | Array[...String]
Default: null

A minimatch pattern, or array of patterns, which specifies the files in the build the plugin should operate on. By default all files are targeted.

Meta

CONTRIBUTING

LICENSE (MIT)


Author: 
Source Code: https://github.com/rollup/plugins/
License: 
#vite #typescript #javascript #rollup 

Kevon  Krajcik

Kevon Krajcik

1657029600

Rollup Plugin Babel: Compile Your Files with Babel With Vite

@rollup/plugin-babel

🍣 A Rollup plugin for seamless integration between Rollup and Babel.

Why?

If you're using Babel to transpile your ES6/7 code and Rollup to generate a standalone bundle, you have a couple of options:

  • run the code through Babel first, being careful to exclude the module transformer, or
  • run the code through Rollup first, and then pass it to Babel.

Both approaches have disadvantages – in the first case, on top of the additional configuration complexity, you may end up with Babel's helpers (like classCallCheck) repeated throughout your code (once for each module where the helpers are used). In the second case, transpiling is likely to be slower, because transpiling a large bundle is much more work for Babel than transpiling a set of small files.

Either way, you have to worry about a place to put the intermediate files, and getting sourcemaps to behave becomes a royal pain.

Using Rollup with @rollup/plugin-babel makes the process far easier.

Requirements

This plugin requires an LTS Node version (v10.0.0+) and Rollup v1.20.0+.

Install

npm install @rollup/plugin-babel --save-dev

Usage

Create a rollup.config.js configuration file and import the plugin:

import { babel } from '@rollup/plugin-babel';

const config = {
  input: 'src/index.js',
  output: {
    dir: 'output',
    format: 'esm'
  },
  plugins: [babel({ babelHelpers: 'bundled' })]
};

export default config;

Then call rollup either via the CLI or the API.

Using With @rollup/plugin-commonjs

When using @rollup/plugin-babel with @rollup/plugin-commonjs in the same Rollup configuration, it's important to note that @rollup/plugin-commonjs must be placed before this plugin in the plugins array for the two to work together properly. e.g.

import { babel } from '@rollup/plugin-babel';
import commonjs from '@rollup/plugin-commonjs';

const config = {
  ...
  plugins: [
    commonjs(),
    babel({ babelHelpers: 'bundled' })
  ],
};

Options

This plugin respects Babel configuration files by default and they are generally the best place to put your configuration.

You can also run Babel on the generated chunks instead of the input files. Even though this is slower, it is the only way to transpile Rollup's auto-generated wrapper code to lower compatibility targets than ES5, see Running Babel on the generated code for details.

All options are as per the Babel documentation, plus the following:

exclude

Type: String | RegExp | Array[...String|RegExp]
 

A minimatch pattern, or array of patterns, which specifies the files in the build the plugin should ignore. When relying on Babel configuration files you can only exclude additional files with this option, you cannot override what you have configured for Babel itself.

include

Type: String | RegExp | Array[...String|RegExp]
 

A minimatch pattern, or array of patterns, which specifies the files in the build the plugin should operate on. When relying on Babel configuration files you cannot include files already excluded there.

filter

Type: (id: string) => boolean
 

Custom filter function can be used to determine whether or not certain modules should be operated upon.

Usage:

import { createFilter } from '@rollup/pluginutils';
const include = 'include/**.js';
const exclude = 'exclude/**.js';
const filter = createFilter(include, exclude, {});

extensions

Type: Array[...String]
Default: ['.js', '.jsx', '.es6', '.es', '.mjs']

An array of file extensions that Babel should transpile. If you want to transpile TypeScript files with this plugin it's essential to include .ts and .tsx in this option.

babelHelpers

Type: 'bundled' | 'runtime' | 'inline' | 'external'
Default: 'bundled'

It is recommended to configure this option explicitly (even if with its default value) so an informed decision is taken on how those babel helpers are inserted into the code.

We recommend to follow these guidelines to determine the most appropriate value for your project:

  • 'runtime' - you should use this especially when building libraries with Rollup. It has to be used in combination with @babel/plugin-transform-runtime and you should also specify @babel/runtime as dependency of your package. Don't forget to tell Rollup to treat the helpers imported from within the @babel/runtime module as external dependencies when bundling for cjs & es formats. This can be accomplished via regex (external: [/@babel\/runtime/]) or a function (external: id => id.includes('@babel/runtime')). It's important to not only specify external: ['@babel/runtime'] since the helpers are imported from nested paths (e.g @babel/runtime/helpers/get) and Rollup will only exclude modules that match strings exactly.
  • 'bundled' - you should use this if you want your resulting bundle to contain those helpers (at most one copy of each). Useful especially if you bundle an application code.
  • 'external' - use this only if you know what you are doing. It will reference helpers on global babelHelpers object. Used in combination with @babel/plugin-external-helpers.
  • 'inline' - this is not recommended. Helpers will be inserted in each file using this option. This can cause serious code duplication. This is the default Babel behavior as Babel operates on isolated files - however, as Rollup is a bundler and is project-aware (and therefore likely operating across multiple input files), the default of this plugin is "bundled".

skipPreflightCheck

Type: Boolean
Default: false

Before transpiling your input files this plugin also transpile a short piece of code for each input file. This is used to validate some misconfiguration errors, but for sufficiently big projects it can slow your build times so if you are confident about your configuration then you might disable those checks with this option.

External dependencies

Ideally, you should only be transforming your source code, rather than running all of your external dependencies through Babel (to ignore external dependencies from being handled by this plugin you might use exclude: 'node_modules/**' option). If you have a dependency that exposes untranspiled ES6 source code that doesn't run in your target environment, then you may need to break this rule, but it often causes problems with unusual .babelrc files or mismatched versions of Babel.

We encourage library authors not to distribute code that uses untranspiled ES6 features (other than modules) for this reason. Consumers of your library should not have to transpile your ES6 code, any more than they should have to transpile your CoffeeScript, ClojureScript or TypeScript.

Use babelrc: false to prevent Babel from using local (i.e. to your external dependencies) .babelrc files, relying instead on the configuration you pass in.

Helpers

In some cases Babel uses helpers to avoid repeating chunks of code – for example, if you use the class keyword, it will use a classCallCheck function to ensure that the class is instantiated correctly.

By default, those helpers will be inserted at the top of the file being transformed, which can lead to duplication. This rollup plugin automatically deduplicates those helpers, keeping only one copy of each one used in the output bundle. Rollup will combine the helpers in a single block at the top of your bundle.

You can customize how those helpers are being inserted into the transformed file with babelHelpers option.

Modules

This is not needed since Babel 7 - it knows automatically that Rollup understands ES modules & that it shouldn't use any module transform with it. Unless you forcefully include a module transform in your Babel configuration.

If you have been pointed to this section by an error thrown by this plugin, please check your Babel configuration files and disable any module transforms when running Rollup builds.

Running Babel on the generated code

You can run @rollup/plugin-babel on the output files instead of the input files by using getBabelOutputPlugin(...). This can be used to perform code transformations on the resulting chunks and is the only way to transform Rollup's auto-generated code. By default, the plugin will be applied to all outputs:

// rollup.config.js
import { getBabelOutputPlugin } from '@rollup/plugin-babel';

export default {
  input: 'main.js',
  plugins: [
    getBabelOutputPlugin({
      presets: ['@babel/preset-env']
    })
  ],
  output: [
    { file: 'bundle.cjs.js', format: 'cjs' },
    { file: 'bundle.esm.js', format: 'esm' }
  ]
};

If you only want to apply it to specific outputs, you can use it as an output plugin (requires at least Rollup v1.27.0):

// rollup.config.js
import { getBabelOutputPlugin } from '@rollup/plugin-babel';

export default {
  input: 'main.js',
  output: [
    { file: 'bundle.js', format: 'esm' },
    {
      file: 'bundle.es5.js',
      format: 'esm',
      plugins: [getBabelOutputPlugin({ presets: ['@babel/preset-env'] })]
    }
  ]
};

The include, exclude and extensions options are ignored when the when using getBabelOutputPlugin and createBabelOutputPluginFactory will produce warnings, and there are a few more points to note that users should be aware of.

You can also run the plugin twice on the code, once when processing the input files to transpile special syntax to JavaScript and once on the output to transpile to a lower compatibility target:

// rollup.config.js
import babel, { getBabelOutputPlugin } from '@rollup/plugin-babel';

export default {
  input: 'main.js',
  plugins: [babel({ presets: ['@babel/preset-react'] })],
  output: [
    {
      file: 'bundle.js',
      format: 'esm',
      plugins: [getBabelOutputPlugin({ presets: ['@babel/preset-env'] })]
    }
  ]
};

Babel configuration files

Unlike the regular babel plugin, getBabelOutputPlugin(...) will not automatically search for Babel configuration files. Besides passing in Babel options directly, however, you can specify a configuration file manually via Babel's configFile option:

getBabelOutputPlugin({
  configFile: path.resolve(__dirname, 'babel.config.js')
});

Using formats other than ES modules or CommonJS

As getBabelOutputPlugin(...) will run after Rollup has done all its transformations, it needs to make sure it preserves the semantics of Rollup's output format. This is especially important for Babel plugins that add, modify or remove imports or exports, but also for other transformations that add new variables as they can accidentally become global variables depending on the format. Therefore it is recommended that for formats other than esm or cjs, you set Rollup to use the esm output format and let Babel handle the transformation to another format, e.g. via

presets: [['@babel/preset-env', { modules: 'umd' }], ...]

to create a UMD/IIFE compatible output. If you want to use getBabelOutputPlugin(...) with other formats, you need to specify allowAllFormats: true as plugin option:

rollup.rollup({...})
.then(bundle => bundle.generate({
  format: 'iife',
  plugins: [getBabelOutputPlugin({
    allowAllFormats: true,
    // ...
  })]
}))

Injected helpers

By default, helpers e.g. when transpiling classes will be inserted at the top of each chunk. In contrast to when applying this plugin on the input files, helpers will not be deduplicated across chunks.

Alternatively, you can use imported runtime helpers by adding the @babel/transform-runtime plugin. This will make @babel/runtime an external dependency of your project, see @babel/plugin-transform-runtime for details.

Note that this will only work for esm and cjs formats, and you need to make sure to set the useESModules option of @babel/plugin-transform-runtime to true if you create ESM output:

rollup.rollup({...})
.then(bundle => bundle.generate({
  format: 'esm',
  plugins: [getBabelOutputPlugin({
    presets: ['@babel/preset-env'],
    plugins: [['@babel/plugin-transform-runtime', { useESModules: true }]]
  })]
}))
// input
export default class Foo {}

// output
import _classCallCheck from '@babel/runtime/helpers/esm/classCallCheck';

var Foo = function Foo() {
  _classCallCheck(this, Foo);
};

export default Foo;

And for CommonJS:

rollup.rollup({...})
.then(bundle => bundle.generate({
  format: 'cjs',
  plugins: [getBabelOutputPlugin({
    presets: ['@babel/preset-env'],
    plugins: [['@babel/plugin-transform-runtime', { useESModules: false }]]
  })]
}))
// input
export default class Foo {}

// output
('use strict');

var _classCallCheck = require('@babel/runtime/helpers/classCallCheck');

var Foo = function Foo() {
  _classCallCheck(this, Foo);
};

module.exports = Foo;

Another option is to use @babel/plugin-external-helpers, which will reference the global babelHelpers object. It is your responsibility to make sure this global variable exists.

Custom plugin builder

@rollup/plugin-babel exposes a plugin-builder utility that allows users to add custom handling of Babel's configuration for each file that it processes.

createBabelInputPluginFactory accepts a callback that will be called with the loader's instance of babel so that tooling can ensure that it using exactly the same @babel/core instance as the loader itself.

It's main purpose is to allow other tools for configuration of transpilation without forcing people to add extra configuration but still allow for using their own babelrc / babel config files.

Example

import { createBabelInputPluginFactory } from '@rollup/plugin-babel';

export default createBabelInputPluginFactory((babelCore) => {
  function myPlugin() {
    return {
      visitor: {}
    };
  }

  return {
    // Passed the plugin options.
    options({ opt1, opt2, ...pluginOptions }) {
      return {
        // Pull out any custom options that the plugin might have.
        customOptions: { opt1, opt2 },

        // Pass the options back with the two custom options removed.
        pluginOptions
      };
    },

    config(cfg /* Passed Babel's 'PartialConfig' object. */, { code, customOptions }) {
      if (cfg.hasFilesystemConfig()) {
        // Use the normal config
        return cfg.options;
      }

      return {
        ...cfg.options,
        plugins: [
          ...(cfg.options.plugins || []),

          // Include a custom plugin in the options.
          myPlugin
        ]
      };
    },

    result(result, { code, customOptions, config, transformOptions }) {
      return {
        ...result,
        code: result.code + '\n// Generated by some custom plugin'
      };
    }
  };
});

Meta

CONTRIBUTING

LICENSE (MIT)


Author: 
Source Code: https://github.com/rollup/plugins/
License: 

#vite #rollup #typescript #javascript