Skip to content
GitLab
Projects Groups Snippets
  • /
  • Help
    • Help
    • Support
    • Community forum
    • Submit feedback
    • Contribute to GitLab
  • Sign in / Register
  • C create-react-app
  • Project information
    • Project information
    • Activity
    • Labels
    • Members
  • Repository
    • Repository
    • Files
    • Commits
    • Branches
    • Tags
    • Contributors
    • Graph
    • Compare
  • Issues 1,547
    • Issues 1,547
    • List
    • Boards
    • Service Desk
    • Milestones
  • Merge requests 417
    • Merge requests 417
  • CI/CD
    • CI/CD
    • Pipelines
    • Jobs
    • Schedules
  • Deployments
    • Deployments
    • Environments
    • Releases
  • Packages and registries
    • Packages and registries
    • Package Registry
    • Infrastructure Registry
  • Monitor
    • Monitor
    • Incidents
  • Analytics
    • Analytics
    • Value stream
    • CI/CD
    • Repository
  • Wiki
    • Wiki
  • Snippets
    • Snippets
  • Activity
  • Graph
  • Create a new issue
  • Jobs
  • Commits
  • Issue Boards
Collapse sidebar
  • Meta
  • create-react-app
  • Merge requests
  • !6505

adding options for esmodules and commonjs build targets (#5216)

  • Review changes

  • Download
  • Email patches
  • Plain diff
Closed Administrator requested to merge github/fork/heygrady/preset-env-targets into master Feb 23, 2019
  • Overview 3
  • Commits 1
  • Pipelines 0
  • Changes 6

Created by: heygrady

Fixes #5216 (closed)

Previous attempt: https://github.com/facebook/create-react-app/pull/5264

Partially related: https://github.com/facebook/create-react-app/pull/6249

This makes it possible to use babel-preset-react-app to create NPM packages. I have an example project using this configuration: https://github.com/zumper/react-ladda

One breaking change is that this changes the default for useESModules to false and also changes what that option means.

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 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 && 'babel-preset-react-app/test',
    // building for lib folder
    useCommonJS &&
      !isEnvTest && [
        'babel-preset-react-app/commonjs',
        { absoluteRuntime: false },
      ],
    // building for es folder
    useESModules && [
      'babel-preset-react-app/esmodules',
      { absoluteRuntime: false },
    ],
    // building for dist folder
    !useCommonJS &&
      !useESModules && ['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 isEnvDevelopment = env === 'development';
  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'),
];
Assignee
Assign to
Reviewers
Request review from
Time tracking
Source branch: github/fork/heygrady/preset-env-targets