npm.io
7.0.1 • Published 3 weeks ago

@anansi/babel-preset

Licence
BSD-3-Clause
Version
7.0.1
Deps
22
Size
141 kB
Vulns
0
Weekly
0
Stars
39

Production ready babel (with TypeScript!)

CircleCI npm downloads npm version PRs Welcome

Configurable production-ready babel preset for React projects with TypeScript support.

This preset is Babel 8-first. Running Babel with it requires a modern Node.js runtime.

Why

  • Up to date best practices
  • Tight multi-plugin configuration
    • Plugins made to interop correctly together
    • Centralized configuration both simplifies and ensures correctness

Usage

Just include in .babelrc

{
  "presets": ["@anansi"]
}

Or configure options

Target node 10
{
  "targets": { "node": "10" },
  "presets": [
    [
      "@anansi"
    ]
  ]
}
Set assumptions
{
  "presets": ["@anansi"],
  "assumptions": {
    "noDocumentAll": true,
    "noClassCalls": true,
    "constantReexports": true,
    "objectRestNoSymbols": true,
    "pureGetters": true
  }
}

React refresh

In dev mode, if react-refresh is installed it will be enabled.

TypeScript

TypeScript files (.ts, .tsx, .mts, .cts, etc) are supported by removing their typings to output javascript that node/browsers can understand. .ts, .mts and .cts files don't parse JSX, so they can use <T>(x: T) => x and <T>value.

Future language support

In addition to providing good production/development/testing transformations; some additional non-standard features are included:

Stage 4
Stage 3
Stage 1

Features

Options

Options to the preset. These are configured like so

{
  "presets": [
    [
      "@anansi",
      {
        "optionName": "optionValue"
      }
    ]
  ]
}
Target Environment
nodeTarget : ?string = undefined

Deprecated: Prefer using top-level targets instead

{
  "targets": { "node": "current" },
  "presets": ["@anansi"]
}

Will run to target node instead of browsers. Specify a valid node string like "current", or "6.15".

If unset, will automatically target current node version when webpack is targetting node.

targets : ?object = undefined

Deprecated: Prefer using top-level targets instead

Use this to override @babel/preset-env targets for non-testing environments. In Babel 8, @babel/preset-env defaults to modern Browserslist targets rather than ES5, so prefer a browserslist config or explicit top-level targets when you need stable output across environments.

Feel free to use the anansi browserlist config.

modules: "amd" | "umd" | "systemjs" | "commonjs" | "cjs" | "auto" | false = false

Enable transformation of ES module syntax to another module type.

By default this tries to infer if ESModules is supported and if so, keep ESM. If this detection isn't working correct, feel free to explicitly set.

BABEL_MODULES

This will override or set modules option from above.

Polyfills

By default we try to conform to these design pricinpals:

  • Libraries prefer to not introduce side-effects
    • Commonjs bundles should require polyfills instead of bundling to:
      • reduce file-size, parse time, and improve JIT opportunities
    • UMD bundles cannot import, therefore should bundle polyfills
  • Applications prefer side-effect versions for simplicity
  • Infer intent by detecting which runtime and polyfill package is explicitly installed in the CWD
polyfillMethod

‘usage-global’ | ‘entry-global’ | ‘usage-pure’ | false | undefined

This determines how to handle polyfills.

plugin reference

undefined

This is the default - it will automatically determine a reasonable default based on other factors.

For app builds with core-js installed:

  1. 'usage-pure' if core-js-pure is installed and your package.json lists core-js-pure in dependencies, peerDependencies or devDependencies without core-js in that same field
  2. Otherwise 'usage-global' if @babel/runtime is installed
  3. Otherwise 'entry-global'

For library builds (@babel/cli, rollup or caller.library is true), or when core-js is not installed: 'usage-pure' if core-js-pure and @babel/runtime-corejs3 are installed, otherwise false.

entry-global

Transforms core-js import into only the polyfills needed for the target environment. This can be best when a good code-splitting strategy for polyfills is in the place.

Turns

import 'core-js'

into

import 'core-js/es/object/has-own'
// whatever else is needed for target env

Like useBuiltins: entry for babel-preset-env.

usage-global

Only imports polyfills as-needed both based on target environment and usage.

import 'core-js/es/object/has-own'
Object.hasOwn({ a: 1 }, 'a')

Like useBuiltins: usage for babel-preset-env.

usage-pure

This doesn't pollute the global scope. This is recommended when bundling libraries.

import _Object$hasOwn from "core-js-pure/stable/object/has-own.js"
_Object$hasOwn({ a: 1 }, 'a')
false

Do not perform any transforms related to core-js or polyfills.

corejsVersion

Specifies the core-js version to target. Without specified will use the version found by importing.

useBuiltIns: "usage" | "entry" | false = "entry"

Deprecated compatibility alias. Prefer polyfillMethod.

This option configures how @anansi/babel-preset handles polyfills. Both usage and entry will only include polyfills needed for the target.

entry allows you to control when/where the polyfills are loaded by adding your own import of core-js. You can even import pieces selectively.

usage will add imports everywhere a file is used, which can make it harder to split polyfills if they are not needed.

runtimePkg = "@babel/runtime"

Can be @babel/runtime-corejs3. Using the corejs version will add imports to the 'pure' form of core-js, which doesn't change global objects. This will however result in heavily increased bundle sizes, so it's generally preferred to stay with the default.

polyfillTargets

POLYFILL_TARGETS env will override this option

Allows for different output targets determining which polyfills to include than what code transforms are applied.

This is sometimes useful when bundling library JS that must work in many environments, but one expects the consumer of the library to handle legacy polyfills themselves.

Safari 15.4 came with Object.hasOwn(). Therefore this would disable inclusion of the Object.hasOwn polyfill (among others).

{
  "presets": [
    [
      "@anansi",
      {
        "polyfillTargets": "safari>15.3"
      }
    ]
  ]
}
Additional Transforms
loose: bool = false

Sets a broad group of top-level assumptions (class fields, spread, template objects and more). Babel 8 removed loose from @babel/preset-env and deprecates it in plugins, so prefer listing the assumptions you want.

decoratorsOptions
  • version: "2023-11" or "legacy" (the only versions Babel 8 supports). defaults to "2023-11"
reactCompiler: {compilationMode?: "annotation"}

Run the React Compiler. Be sure to check compatibility before turning this on.

By default does not run. Include empty object or a configuration to turn on.

** Requires React 19+ **

** This only runs in production **

reactConstantElementsOptions: { allowMutablePropsOnTags?: string[] } | false

Configures the options for react-constant-elements. Setting to false disables this optimization altogether. Note: this is only ever used in production mode

hasJsxRuntime

** Defaults to true. Set this to false explicitly to use with React <=16.13 **

Use new jsx transform. Available in React >16.14.

  • With the new transform, you can use JSX without importing React.
  • Depending on your setup, its compiled output may slightly improve the bundle size.
  • It will enable future improvements that reduce the number of concepts you need to learn React.

Note: This is automatically set when using anansi webpack using the caller config

developmentSourceSelf: bool

Adds __source/__self to development JSX. React 19.2 stopped using them, so this defaults to true only for React < 19.2. @anansi/webpack-config and @anansi/jest-preset detect the version for you; otherwise it is read from the react installed at the current directory.

tsConfigPath

Specifies the tsconfig.json file location to automatically apply tsconfig path mapping.

.babelrc.js
module.exports = {
  presets: [['@anansi', { tsConfigPath: '.' }]],
};

Merges with module resolver options

TS_CONFIG_PATH

Overrides tsConfigPath.

export TS_CONFIG_PATH = './tsconfig.json'
module-resolver options
resolverRoot

Sets the root root.

root = ['./src'];
RESOLVER_ROOT

Overrides resolverRoot.

export RESOLVER_ROOT = './src'
resolverAlias

JSON representation of the alias object option.

{
  "underscore": "lodash",
  "^@namespace/foo-(.+)": "packages/\\1"
}
RESOLVER_ALIAS

If RESOLVER_ALIAS env is set, it will override this setting. Be sure to JSON encode.

export RESOLVER_ALIAS = '{"underscore":"lodash","^@namespace/foo-(.+)":"packages/\\\\1"}'
resolver

Full control of module-resolver options. Sets as default, so resolverRoot and resolverAlias will override root and alias respectively.

root-import options
rootPathSuffix: string = './src'

Enables importing from project root with ~/my/path rather than using relative paths. Override this if your project root is in another directory.

This is the recommended way to manage imports in larger libraries.

When using with typescript, be sure to add to tsconfig.json:

{
  "baseUrl": "./src",
  "paths": { "~/*": ["*"] }
}
rootPathPrefix: string = '~/'

Configures what prefix is used to trigger root imports.

rootPathRoot: undefined

Controls the root. No value (undefined) means use current working directory.

Sending __dirname from a .babelrc.js can be useful to ensure consistency no matter where babel starts running from.

Keywords