Search code examples
javascriptwebpackbabeljsbabel-loader

Best practices with transpiled JS codebase: included in git or generated during installation process?


I'm creating a JS library (using Babel and Webpack) for:

  • node.js
  • the browser.

Is it recommended to include the transpiled files from Babel and webpack in the codebase? Since, at least for the backend side, another project installing that library might not have Babel (particularly to avoid issue like SyntaxError: Cannot use import statement outside a module)

I was thinking of generating theses distributions file during the NPM installation process, but I don't think it's a good idea to move babel and webpack from devDependencies to dependencies in the packages.json.

The project structure is looking at this:

project-directory
|--dist
|  |--index.js
|--node_modules
|--src
|  |--index.js
|--package.json
|--.babelrc

Solution

  • After playing with npm publish, I think I found the right way.

    The codebase should not contain the dist/ directory (excluded in .gitignore).

    When publishing, npm publish will create a package containing your dist/ directory (like git, you have a .npmignore to exclude elements you don't want in your package).

    In the packages.json, the main property should point to the main transpiled .js file. Adding a prepack script will ensure that your transpiled code is up to date before publishing a new package.

    {
      "main": "dist/index.js",
      "module": "src/index.js",
      "scripts": {
        "prepack": "npm run build",
        "build": "babel src --out-dir dist"
      },
      "devDependencies": {
        "@babel/cli": "^7.7.5",
        "@babel/core": "^7.7.5",
        "@babel/node": "^7.7.4",
        "@babel/preset-env": "^7.7.6"
      }
    }