Precompile jsx for React in django-compressor

585 views Asked by At

Using Cygwin on Windows 10 (64 bits) Installed babel-cli, react and babel-preset-react on top of Node.js, which was installed via Windows Installer (since there is no support for Cygwin.) I installed those Node packages using yarn, in the global modules folder.

In the django-compressor documentation (https://django-compressor.readthedocs.io/en/latest/reactjs/) they say that a precompiler setting does the trick:

COMPRESS_PRECOMPILERS = (
   ('text/jsx', 'cat {infile} | babel > {outfile}'),
)

However, babel is not recognizing jsx (throwing errors when encountering virtual dom elements.) It's obvious because I am not passing the react preset to the command. But there is no way I can use that preset because I installed in the global module folder and now I am unable to make babel find and use it.

I need one of these possible solutions:

  1. How can I make babel use a preset globally installed (how should I use babel --presets react in a way that works)?

  2. How do I use a .babelrc file in a Django project?

  3. If I were to install the preset locally (which I seem to dislike a lot) how do I make it live with my Django project without making mess out of my project directory structure?

1

There are 1 answers

0
Lorenzo Peña On BEST ANSWER

Okay, I banged my head a few times and found a solution:

  1. There is no way to make babel work with presets installed globally. It is mandatory to install them locally. All react, react-dom, babel-core, babel-loader, babel-preset-react (and perhaps babel-preset-es2015 if latest ECMA syntax is desired) must be installed locally.

  2. There is no place to put a .babelrc file where the precompiler would use it. No use to have a babel section in package.json either. Instead, the precompiler setting should pass the presets in command line like:

    COMPRESS_PRECOMPILERS = (
      ('text/jsx', 'cat {infile} | babel --presets react,es2015 > {outfile}'),
    )
    
  3. Just assume that the folder where manage.py lives is also the root for Nodejs packages. Not tested when deployed and running from a wsgi file but maybe the wsgi should also live next to manage.py.

Also, it looks like all these files and folders: node_modules, package.json and yarn.lock (if installing with yarn as I am,) must be included in version control.

EDITED: I no loger think node_modules should go into version control.