Search code examples
ecmascript-6jsxbabeljsbabel-cli

Stop Babel compiling jsx code?


Most information and answers deal with issues of babel not compiling into JSX. In my case, I use .jsx as a templating engine, so I want babel to compile .js files but not .jsx files. Still I want to copy the files to a build/dist folder.

My app structure is:

App/
├── dist/
├── styles/
│   ├── _main.scss
│   ├── _module.scss
│   └── index.scss
├── assets/
│   ├── index.css
│   └── image.jpg
├── views/
│   ├── main.jsx
│   └── component.jsx
├── server.js
├── Models.js
├── Schemas.js
└── package.json

I have tried

babel src -d dist --ignore styles,*.jsx --copy-files views --presets es2015

It does not seem to recognize views folder

babel src -d dist --ignore styles --copy-files --presets es2015

It does things correctly, but also compiles .jsx, which breaks the views.

I also thought about removing the babel-loader package, but not sure if that is overdoing it.

I can't think of more information that you may need to answer, but let me know if you want me to put the package.json or any other files.

Update

There seems to be some confusion surrounding --ignore and --copy-files. Some people expect ignore to override copy and others copy to override ignore. In my case the latter will be preferable.

https://github.com/babel/babel/issues/5052 https://github.com/babel/babel/issues/5176

Now, if I do this

babel src --out-dir dist --copy-files --ignore styles,*jsx  --presets es2015

It ignores .jsx files, but it doesn't copy them. It does ignore styles directory, which is correct. It seems that it is incapable of ignoring something it can transpile.


Solution

  • --copy-files option copies the files that weren't processed 'as is'. It doesn't accept which files they are like --copy-files views.

    --ignore option ignores files entirely, which is undesirable behaviour here.

    The problem is that Babel processes .jsx files, not that it compiles JSX. Babel doesn't compile JSX syntax if react preset isn't specified, so it is perceived as syntax errors. This happens because it processes .jsx files by default. The solution is to override defaults with --extensions option:

    babel src -d dist --extensions .js --copy-files --presets es2015
    

    This should transpile all .js files from ES6 to ES5 and just copy everything else.

    It should be mentioned that Babel is just a transpiler and may be not the right tool for complex file manipulation tasks. This is what dedicated automation tools like Grunt and Gulp are for.