Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compile all included files into one using Babel?

I am using Babel in my project. The thing is, I have this line of code in my server.js:

import schema from "./data/schema";

(data/schema.js is in ES2015 syntax).

And when I am trying to compile my server.js with babel, like this:

babel -o server_production.js --minified  server.js

it produces a new file without errors and replaces import instruction with require. But the thing is, when I am trying to run my babel-compiled server.js with node, it complains about data/schema.js, because it wasn't transpiled into ES5, only required (the exact error is Unexpected token "import", because I am using some other imports in data/schema.js).

So, the question is: how can I compile my file and all the files it imports into one file? I tried babel -o server_production.js --minified data/schema.js server.js, but that didn't work either.

like image 368
serge1peshcoff Avatar asked Sep 13 '16 13:09

serge1peshcoff


People also ask

How do you compile with babel?

Simply add a "scripts" field to your package. json and put the babel command inside there as build . This will run Babel the same way as before and the output will be present in lib directory, only now we are using a local copy. Alternatively, you can reference the babel cli inside of node_modules .

How do you use a babel transpiler?

You can use babel-standalone to transpile ES6 to ES5 in a browser environment. You just need to load the “babel-standalone” in your script as highlighted below and write the script you want to transpile, in script tag with type “text/babel” or “text/jsx”. Babel will automatically compile and execute the script.


1 Answers

Babel doesn't bundle dependencies by default. You'll need to use a module bundler like rollup.

To do this, you'll need to define a rollup config similar to this one:

rollup.config.js

import babel from 'rollup-plugin-babel';
import babelrc from 'babelrc-rollup';

export default {
  entry: 'server.js',
  dest: 'server_production.js',
  plugins: [
    babel(babelrc())
  ]
};

This works with the package.json file defined below:

{
  "scripts": {
    "rollup": "./node_modules/.bin/rollup -c"
  },
  "devDependencies": {
    "babel-cli": "6.14.0",
    "babel-plugin-external-helpers": "6.8.0",
    "babel-preset-es2015": "6.14.0",
    "babelrc-rollup": "3.0.0",
    "rollup": "0.35.10",
    "rollup-plugin-babel": "2.6.1"
  }
}

You execute the command npm run rollup -c to bundle and compile the files.

You'll find an example here: https://ide.c9.io/ifeanyidev/babel-rollup-example

like image 191
gnerkus Avatar answered Oct 04 '22 05:10

gnerkus