babel config not working in project as npm package

Created an npm package with the following babel.config.json file:

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ],
  "plugins": [
    "@babel/plugin-syntax-jsx"
  ]
}

And when importing this package in another project, i get following error:

experimental syntax 'jsx' isn't currently enabled

How can i fix this?


So,

  1. An npm package needs to be compiled / transpiled before it can be used as an npm package. Why? Because both jsx and Typescript requires build tools to be converted into runnable code in NodeJS and an npm package should come without assumptions on such tools. Use Babel or tsc to transpile your source files into an output folder out in your project. You can also use Webpack to transpile and bundle your package even though typically, the sources are not bundled in a package because it hampers the possibilities to tree-shake.

    Pay attention to whether you want the npm package to offer esm (ES, es6) or cjs (CommonJS) modules and whether you want to include types or not. cjs is the more traditional approach whereas esm is newer. Use cjs to begin with if you don't know what you're doing so far since esm can be trickier to consume. You can also supply both of these variants in your package.

    Read about this process in the documentation of Babel, tsc and Webpack but you WILL have to run the babel, tsc or webpack commands to get the transpiled file(s).

    EDIT: It might be possible to keep jsx and Typescript in an npm package but it is absolutely not how it is usually done. For example, with ts-loader (often used to process Typescript files in Webpack) there is the setting allowTsInNodeModules. It seems however that it would require quite a lot of more configuration and it's unclear what advantage this strategy has.

  2. Add a package.json to the out folder. Usually we use package.json in a project to determine what to download for our project and so on but at the root of an npm package there should also be a package.json. This file determines what dependencies your package has but also what kind of package it is, its entrypoint, whether it has types and much more: https://docs.npmjs.com/cli/v8/configuring-npm/package-json

  3. You now have an npm package in the out folder. Either publish it to an npm registry (the most common and the default being npmjs.org but others, private and public exist too) OR hot-link it locally to another project with npm: https://docs.npmjs.com/cli/v8/commands/npm-link

You have now taken your first steps in package building. It's a big and quite complicated subject once you get into different kind of modules and tree-shaking and npm inner workings, so be patient and take one thing at a time.

PS! The out folder can be named something else as well ;) DS