title: How can I publish an NPM module with both commonjs and es6 versions?
body: <p>I have a module I want to publish to npm.  I have found some &quot;solutions&quot; that are 4+ years old, examples using babel 5.x, and other problems that made the examples not work as shown.</p>
  <p>Ideally I want to write my code using es6 and build/transpile with babel such that it can be imported with <code>require()</code> in scripts or <code>import</code> in modules.</p>
  <p>Right now, here's my (sample) module that shows what I've tried.</p>
  <pre><code>// index.js
  export default function speak () {
    console.log(&quot;Hello, World!&quot;);
  }
  </code></pre>
  <pre><code>// .babelrc
  {
    &quot;comments&quot;:false,
    &quot;presets&quot;: [
        [&quot;@babel/env&quot;, {&quot;modules&quot;: &quot;commonjs&quot;}]
    ],
    &quot;plugins&quot;: [
      &quot;@babel/plugin-transform-modules-commonjs&quot;,
      &quot;add-module-exports&quot;
    ]
  }
  </code></pre>
  <pre><code>// package.json
  {
    &quot;name&quot;: &quot;foo&quot;,
    &quot;version&quot;: &quot;1.0.0&quot;,
    &quot;description&quot;: &quot;&quot;,
    &quot;main&quot;: &quot;index.js&quot;,
    &quot;scripts&quot;: {
      &quot;build&quot;: &quot;babel index.js -d dist&quot;
    },
    &quot;keywords&quot;: [],
    &quot;author&quot;: &quot;&quot;,
    &quot;license&quot;: &quot;ISC&quot;,
    &quot;devDependencies&quot;: {
      &quot;@babel/cli&quot;: &quot;^7.10.5&quot;,
      &quot;@babel/core&quot;: &quot;^7.10.5&quot;,
      &quot;@babel/plugin-transform-modules-commonjs&quot;: &quot;^7.10.4&quot;,
      &quot;@babel/preset-env&quot;: &quot;^7.10.4&quot;,
      &quot;babel-plugin-add-module-exports&quot;: &quot;^1.0.2&quot;
    }
  }
  </code></pre>
  <p>And, finally, a demo script (demo.js)</p>
  <pre><code>// demo.js
  const speak = require('./dist/index.js');
  speak();
  </code></pre>
  <p>When I do <code>npm run build</code> and then <code>node demo.js</code>, it works as expected:</p>
  <pre><code>Hello, World!
  </code></pre>
  <p>I would also like to be able to have a module (add <code>&quot;type&quot;:&quot;module&quot;</code> to package.json) and then use a demo.js file this way:</p>
  <pre><code>import speak from './dist/index.js';
  speak();
  </code></pre>
  <p>However, I get this an error that a default export isn't available:</p>
  <pre><code>import speak from './dist/index.js';
         ^^^^^
  SyntaxError: The requested module './dist/index.js' does not provide an export named 'default'
  </code></pre>
  <p>I don't really care what the answer is, I'd just like to know what the best practices are.  Should I just export as ES6?  Should I just require commonjs?  Is there a way of transpiling with two available targets?</p>
  <p><em>Note:</em></p>
  <ul>
  <li><em>node v14.5.0</em></li>
  <li><em>npm  v6.14.6</em></li>
  <li><em>@babel/core v7.10.5</em></li>
  </ul>