Search code examples
javascriptrollup

What's the reason Rollup build Js into two files cjs and es


Recently I saw a package that has two built files.

index.es.js    
index.js

enter image description here

I am curious why there are two Js files.

When I import the package

import test from 'this-package';

which file will be used and how it determine which file to be imported?


Solution

  • The file you get when doing a default import is documented in the package.json of that package (as in most npm packages) in the "main" property.

    The reason you have two formats is that not every build environment supports ECMAScript Modules (import/export syntax, .es.js), e.g. node until version 11 didn't support import syntax, and thus, a fallback in the form of a CommonJS module is made available for your convenience.