Skip to content

Instantly share code, notes, and snippets.

@d9k
Last active August 15, 2017 02:56
Show Gist options
  • Save d9k/651a7f926e85cbbfbf32631983529ea2 to your computer and use it in GitHub Desktop.
Save d9k/651a7f926e85cbbfbf32631983529ea2 to your computer and use it in GitHub Desktop.
Babel compressor for jinja assets compiler (see https://github.com/jaysonsantos/jinja-assets-compressor/issues/51)

Got to work with local node_modules installation.

  1. At your app folder: npm install --save babel-cli babel-preset-es2015 babel-preset-react babel-preset-stage-0
  2. manual run to test babel installation: node_modules/.bin/babel --presets=es2015,stage-0,react

input:

let a = 5; console.log(a);

after new empty line press Ctrl+D (EOF)

Expected output:

"use strict";

var a = 5;
console.log(a);
  1. create babel_compressor.py from this gist: https://gist.github.com/d9k/651a7f926e85cbbfbf32631983529ea2
  2. usage (at your web app entry point):
# change your.path.to.babel_compressor to actual path
from your.path.to.babel_compressor import BabelCompressor
from jac.config import Config as JacDefaultConfig

# . . . . .
# right before app initialization:

    # check paths with debugger!
    BabelCompressor.binary = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'node_modules', '.bin', 'babel'))
    BabelCompressor.cwd_for_presets_search = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
    jac_default_config = JacDefaultConfig()
    # get jinja2_env. In Pyramid you can get it this way:
    # `jinja2_env = pyramid_jinja2.get_jinja2_environment(config)`
    jinja2_env.compressor_classes = jac_default_config.get('compressor_classes')
    jinja2_env.compressor_classes['text/babel'] = BabelCompressor

  1. at your jinja2 template code:
    {% compress 'js' %}
    <script type="text/babel">
        let a = 5;
        console.log(a);
    </script>
    {% endcompress %}
# -*- coding: utf-8 -*-
import errno
import subprocess
from rjsmin import jsmin
from jac.compat import file, u, utf8_encode
from jac.exceptions import InvalidCompressorError
class BabelCompressor(object):
"""Compressor for text/babel mimetype (see https://babeljs.io/docs/setup/#installation).
Uses the babel command line program to generate JavaScript, then
uses rjsmin for minification.
TODO does babel have it's own minification?
"""
binary = 'babel'
"""
to fix error Couldn't find preset "xxxxx" relative to directory ...
define here any path inside the folder containing "node_modules" with babel executable
"""
cwd_for_presets_search = None
presets = ['es2015', 'stage-0', 'react']
extra_args = []
@classmethod
def compile(cls, what, mimetype='text/babel', cwd=None, uri_cwd=None,
debug=None):
args = ['--presets=' + ",".join(cls.presets)]
if cls.extra_args:
args.extend(cls.extra_args)
args.insert(0, cls.binary)
try:
handler = subprocess.Popen(args, stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=cls.cwd_for_presets_search)
except OSError as e:
msg = '{0} encountered an error when executing {1}: {2}'.format(
cls.__name__,
cls.binary,
u(e),
)
if e.errno == errno.ENOENT:
msg += ' Make sure {0} is in your PATH.'.format(cls.binary)
raise InvalidCompressorError(msg)
if isinstance(what, file):
what = what.read()
(stdout, stderr) = handler.communicate(input=utf8_encode(what))
stdout = u(stdout)
if not debug:
stdout = jsmin(stdout)
if handler.returncode == 0:
return stdout
else:
raise RuntimeError('Test this :S %s' % stderr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment