@zumper/babel-preset-react-app

9.1.1-zumper.25 • Public • Published

@zumper/babel-preset-react-app

This is a fork of babel-preset-react-app that adds additional options for commonjs and esmodules targets. See usage with Rollup below.


This package includes the Babel preset used by Create React App.
Please refer to its documentation:

Usage in Create React App Projects

The easiest way to use this configuration is with Create React App, which includes it by default. You don’t need to install it separately in Create React App projects.

Note: @zumper/babel-preset-react-app is included by default with @zumper/react-scripts, a custom fork of Create React App.

Usage Outside of Create React App

If you want to use this Babel preset in a project not built with Create React App, you can install it with the following steps.

First, install Babel.

Then install @zumper/babel-preset-react-app.

yarn add --dev @zumper/babel-preset-react-app

Then create a file named .babelrc with following contents in the root folder of your project:

{
  "presets": ["@zumper/babel-preset-react-app"]
}

This preset uses the useBuiltIns option with transform-object-rest-spread and transform-react-jsx, which assumes that Object.assign is available or polyfilled.

Usage with Flow

Make sure you have a .flowconfig file at the root directory. You can also use the flow option on .babelrc:

{
  "presets": [
    ["@zumper/babel-preset-react-app", { "flow": true, "typescript": false }]
  ]
}

Usage with TypeScript

Make sure you have a tsconfig.json file at the root directory. You can also use the typescript option on .babelrc:

{
  "presets": [
    ["@zumper/babel-preset-react-app", { "flow": false, "typescript": true }]
  ]
}

Usage with Rollup

If you are creating an NPM package that contains a React component you can use the options for commonjs and esmodules to create proper builds for lib, es and dist folders. The configuration example below will work for most common cases but will not be suitable to all projects. Similar setups are used by popular NPM packages such as react-redux and react-router.

package.json

This is a simplified package.json file showing how the build script might be configured.

Notably absent from the example file below are any dependencies and jest configuration. You can see a more complete example in the @zumper/react-ladda package.

{
  "name": "my-package-name",
  "version": "1.0.0",
  "main": "lib/index.js",
  "unpkg": "dist/my-package-name.js",
  "module": "es/index.js",
  "files": ["dist", "lib", "src", "es"],
  "scripts": {
    "build:commonjs": "cross-env MODULES_ENV=commonjs babel src --out-dir lib",
    "build:es": "cross-env MODULES_ENV=esmodules babel src --out-dir es",
    "build:umd": "rollup -c",
    "build": "yarn build:commonjs && yarn build:es && yarn build:umd",
    "clean": "rimraf lib dist es coverage",
    "prepare": "yarn clean && yarn build",
    "test": "jest"
  }
}

babel.config.js

When building for lib, es folders you want to set the absoluteRuntime to false. Letting the absoluteRuntime default to true will include the full local path to the runtime in your build, which is undesirable for a published NPM package. When building for the dist folder, you also want to disable helpers (because Rollup manages helpers automatically).

Note that it is recommended to set NODE_ENV environment variable to "production" when building an NPM package. Setting NODE_ENV to "development" will put the @babel/preset-react plugin into development mode, which is undesirable for a published NPM package.

const { NODE_ENV, MODULES_ENV } = process.env;

const isEnvTest = NODE_ENV === 'test';
if (!isEnvTest) {
  // force production mode for package builds
  process.env.NODE_ENV = 'production';
}

const useCommonJS = isEnvTest || MODULES_ENV === 'commonjs';
const useESModules = MODULES_ENV === 'esmodules';

module.exports = {
  presets: [
    // for testing with jest/jsdom
    useCommonJS && isEnvTest && '@zumper/babel-preset-react-app/test',
    // building for lib folder
    useCommonJS &&
      !isEnvTest && [
        '@zumper/babel-preset-react-app/commonjs',
        { absoluteRuntime: false },
      ],
    // building for es folder
    useESModules && [
      '@zumper/babel-preset-react-app/esmodules',
      { absoluteRuntime: false },
    ],
    // building for dist folder
    !useCommonJS &&
      !useESModules && ['@zumper/babel-preset-react-app', { helpers: false }],
  ].filter(Boolean),
};

rollup.config.js

import babel from 'rollup-plugin-babel';
import replace from 'rollup-plugin-replace';
import commonjs from 'rollup-plugin-commonjs';
import nodeResolve from 'rollup-plugin-node-resolve';
import { terser } from 'rollup-plugin-terser';

import camelCase from 'lodash.camelcase';
import kebabCase from 'lodash.kebabcase';
import upperFirst from 'lodash.upperfirst';

import pkg from './package.json';

const input = 'src/index.js';
const globalName = upperFirst(camelCase(pkg.name));
const fileName = kebabCase(pkg.name);

const deps = [
  ...Object.keys(pkg.dependencies || {}).filter(
    key => key !== '@babel/runtime'
  ),
  ...Object.keys(pkg.peerDependencies || {}),
];
const external = name => deps.some(dep => name.startsWith(dep));
const globals = {
  react: 'React',
  'prop-types': 'PropTypes',
  // ... add other external UMD package names here
};

const createConfig = env => {
  const isEnvProduction = env === 'production';
  return {
    input,
    output: {
      file: `dist/${fileName}${isEnvProduction ? '.min' : ''}.js`,
      format: 'umd',
      name: globalName,
      indent: false,
      exports: 'named',
      globals,
    },
    external,
    plugins: [
      nodeResolve({
        extensions: ['.mjs', '.js', '.jsx', '.ts', '.tsx', '.json'],
      }),
      babel(),
      commonjs(),
      replace({ 'process.env.NODE_ENV': JSON.stringify(env) }),
      isEnvProduction &&
        terser({
          compress: {
            pure_getters: true,
            unsafe: true,
            unsafe_comps: true,
            warnings: false,
          },
        }),
    ].filter(Boolean),
  };
};

export default [
  // UMD Development
  createConfig('development'),
  // UMD Production
  createConfig('production'),
];

Readme

Keywords

none

Package Sidebar

Install

npm i @zumper/babel-preset-react-app

Weekly Downloads

7

Version

9.1.1-zumper.25

License

MIT

Unpacked Size

34.1 kB

Total Files

13

Last publish

Collaborators

  • dloehr