Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from

Conversation

heygrady
Copy link
Contributor

@heygrady heygrady commented Feb 23, 2019

Fixes #5216

Previous attempt: #5264

Partially related: #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'),
];

Copy link
Contributor Author

@heygrady heygrady left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some open questions

const env = process.env.BABEL_ENV || process.env.NODE_ENV;
return create(
api,
Object.assign({ helpers: false }, opts, { useESModules: true }),
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this default absolutRuntime to false?

const env = process.env.BABEL_ENV || process.env.NODE_ENV;
return create(
api,
Object.assign({ helpers: false }, opts, { useCommonJS: true }),
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this default absolutRuntime to false?

targets: {
node: 'current',
},
targets,
// Do not transform modules to CJS
modules: false,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be true for tests?

@@ -35,6 +37,7 @@
"babel-loader": "8.0.5",
"babel-plugin-dynamic-import-node": "2.2.0",
"babel-plugin-macros": "2.5.0",
"babel-plugin-transform-dynamic-import": "2.1.0",
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This plugin was missing 🤷

@stale
Copy link

stale bot commented Apr 23, 2019

This pull request has been automatically marked as stale because it has not had any recent activity. It will be closed in 5 days if no further activity occurs.

@stale stale bot added the stale label Apr 23, 2019
@stale
Copy link

stale bot commented Apr 28, 2019

This pull request has been automatically closed because it has not had any recent activity. If you have a question or comment, please open a new issue. Thank you for your contribution!

@stale stale bot closed this Apr 28, 2019
@lock lock bot locked and limited conversation to collaborators May 3, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

babel-preset-react-app doesn't support overriding targets
2 participants