示例#1
0
def autoprefixer(css, is_file=None, options=None):
    if is_file:
        with open(css, 'r') as content_file:
            css = content_file.read()

    try:
        return js_host_function.call(css=css, options=options)
    except FunctionError as e:
        six.reraise(AutoprefixerError, AutoprefixerError(*e.args),
                    sys.exc_info()[2])
def webpack(config_file, watch_config=None, watch_source=None):
    if not settings.BUNDLE_ROOT:
        raise ImproperlyConfigured('webpack.conf.settings.BUNDLE_ROOT has not been defined.')

    if not settings.BUNDLE_URL:
        raise ImproperlyConfigured('webpack.conf.settings.BUNDLE_URL has not been defined.')

    if not os.path.isabs(config_file):
        abs_path = staticfiles.find(config_file)
        if not abs_path:
            raise ConfigFileNotFound(config_file)
        config_file = abs_path

    if not os.path.exists(config_file):
        raise ConfigFileNotFound(config_file)

    if watch_config is None:
        watch_config = settings.WATCH_CONFIG_FILES

    if watch_source is None:
        watch_source = settings.WATCH_SOURCE_FILES

    try:
        output = js_host_function.call(
            config=config_file,
            watch=watch_source,
            watchDelay=settings.WATCH_DELAY,
            watchConfig=watch_config,
            cache=False,
            fullStats=settings.OUTPUT_FULL_STATS,
            bundleDir=settings.get_path_to_bundle_dir(),
        )
    except FunctionError as e:
        raise six.reraise(BundlingError, BundlingError(*e.args), sys.exc_info()[2])

    stats = json.loads(output)

    if stats['errors']:
        raise BundlingError(
            '{}\n\n{}'.format(config_file, '\n\n'.join(stats['errors']))
        )

    if stats['warnings']:
        warnings.warn(stats['warnings'], WebpackWarning)

    # Generate contextual information about the generated assets
    stats['urlsToAssets'] = {}
    path_to_bundle_dir = settings.get_path_to_bundle_dir()
    for asset, config_file in six.iteritems(stats['pathsToAssets']):
        if path_to_bundle_dir in config_file:
            rel_path = config_file[len(path_to_bundle_dir):]
            rel_url = pathname2url(rel_path)
            if rel_url.startswith('/'):
                rel_url = rel_url[1:]
            url = '{}{}/{}/{}'.format(settings.BUNDLE_URL, settings.OUTPUT_DIR, settings.BUNDLE_DIR, rel_url)
            stats['urlsToAssets'][asset] = url

    return WebpackBundle(stats)
示例#3
0
def render_component(
        # Rendering options
        path,
        props=None,
        to_static_markup=None,
        # Bundling options
        bundle=None,
        translate=None,
        # Prop handling
        json_encoder=None):
    if not os.path.isabs(path):
        abs_path = staticfiles.find(path)
        if not abs_path:
            raise ComponentSourceFileNotFound(path)
        path = abs_path

    if not os.path.exists(path):
        raise ComponentSourceFileNotFound(path)

    bundled_component = None
    if bundle or translate:
        bundled_component = bundle_component(path, translate=translate)
        path = bundled_component.get_paths()[0]

    if json_encoder is None:
        json_encoder = JSONEncoder

    if props is not None:
        serialized_props = json.dumps(props, cls=json_encoder)
    else:
        serialized_props = None

    try:
        markup = js_host_function.call(path=path,
                                       serializedProps=serialized_props,
                                       toStaticMarkup=to_static_markup)
    except FunctionError as e:
        raise six.reraise(ReactRenderingError, ReactRenderingError(*e.args),
                          sys.exc_info()[2])

    return RenderedComponent(markup, path, props, serialized_props,
                             bundled_component, to_static_markup)
示例#4
0
def render_component(
    # Rendering options
    path, props=None, to_static_markup=None,
    # Bundling options
    bundle=None, translate=None,
    # Prop handling
    json_encoder=None
):
    if not os.path.isabs(path):
        abs_path = staticfiles.find(path)
        if not abs_path:
            raise ComponentSourceFileNotFound(path)
        path = abs_path

    if not os.path.exists(path):
        raise ComponentSourceFileNotFound(path)

    bundled_component = None
    if bundle or translate:
        bundled_component = bundle_component(path, translate=translate)
        path = bundled_component.get_paths()[0]

    if json_encoder is None:
        json_encoder = JSONEncoder

    if props is not None:
        serialized_props = json.dumps(props, cls=json_encoder)
    else:
        serialized_props = None

    try:
        markup = js_host_function.call(
            path=path,
            serializedProps=serialized_props,
            toStaticMarkup=to_static_markup
        )
    except FunctionError as e:
        raise six.reraise(ReactRenderingError, ReactRenderingError(*e.args), sys.exc_info()[2])

    return RenderedComponent(markup, path, props, serialized_props, bundled_component, to_static_markup)
示例#5
0
def webpack_template_tag(path_to_config):
    """
    A template tag that will output a webpack bundle.

    Usage:

        {% load webpack %}
        
        {% webpack 'path/to/webpack.config.js' as bundle %}

        {{ bundle.render_css|safe }}

        {{ bundle.render_js|safe }}
    """

    # TODO: allow selection of entries

    # Django's template system silently fails on some exceptions
    try:
        return webpack(path_to_config)
    except (AttributeError, ValueError) as e:
        raise six.reraise(BundlingError, BundlingError(*e.args), sys.exc_info()[2])
示例#6
0
def render_route(
    # Rendering options
    path, # path to routes file
    client_path, # path to client routes file
    request, # pass in request object
    props=None,
    to_static_markup=None,
    # Bundling options
    bundle=None,
    translate=None,
    # Prop handling
    json_encoder=None
):
    if not os.path.isabs(path):
        abs_path = staticfiles.find(path)
        if not abs_path:
            raise ComponentSourceFileNotFound(path)
        path = abs_path

    if not os.path.exists(path):
        raise ComponentSourceFileNotFound(path)

    if not os.path.isabs(client_path):
        abs_client_path = staticfiles.find(client_path)
        if not abs_client_path:
            raise ComponentSourceFileNotFound(client_path)
        client_path = abs_client_path

    if not os.path.exists(client_path):
        raise ComponentSourceFileNotFound(client_path)

    bundled_component = None
    import re
    client_re = re.compile(r"client-(?:\w*\d*).js",re.IGNORECASE)
    server_re = re.compile(r"server-(?:\w*\d*).js",re.IGNORECASE)
    if bundle or translate:
        bundled_component = bundle_component(path, client_path, translate=translate)
        assets = bundled_component.get_assets()
        for asset in assets:
            m = client_re.search(asset['name'])
            if m:
                client_path = asset['path']
            m = server_re.search(asset['name'])
            if m:
                path = asset['path']

    if json_encoder is None:
        json_encoder = JSONEncoder

    if props is not None:
        serialized_props = json.dumps(props, cls=json_encoder)
    else:
        serialized_props = None

    try:
        location = {
            'pathname': request.path,
            'query': request.GET.dict()
        }
        cbData = json.loads(js_host_function.call(
            path=path,
            location=location,
            serializedProps=serialized_props,
            toStaticMarkup=to_static_markup
        ))
    except FunctionError as e:
        raise six.reraise(ReactRenderingError, ReactRenderingError(*e.args), sys.exc_info()[2])

    if cbData['match']:
        return RouteRenderedComponent(cbData['markup'], client_path, props, serialized_props, bundled_component, to_static_markup)
    else:
        if cbData['redirectInfo']:
            return RouteRedirect(**cbData['redirectInfo'])
        else:
            return RouteNotFound()
示例#7
0
def webpack(config_file, watch_config=None, watch_source=None):
    if not settings.BUNDLE_ROOT:
        raise ImproperlyConfigured(
            'webpack.conf.settings.BUNDLE_ROOT has not been defined.')

    if not settings.BUNDLE_URL:
        raise ImproperlyConfigured(
            'webpack.conf.settings.BUNDLE_URL has not been defined.')

    if not os.path.isabs(config_file):
        abs_path = staticfiles.find(config_file)
        if not abs_path:
            raise ConfigFileNotFound(config_file)
        config_file = abs_path

    if not os.path.exists(config_file):
        raise ConfigFileNotFound(config_file)

    if watch_config is None:
        watch_config = settings.WATCH_CONFIG_FILES

    if watch_source is None:
        watch_source = settings.WATCH_SOURCE_FILES

    try:
        output = js_host_function.call(
            config=config_file,
            watch=watch_source,
            watchDelay=settings.WATCH_DELAY,
            watchConfig=watch_config,
            cache=False,
            fullStats=settings.OUTPUT_FULL_STATS,
            bundleDir=settings.get_path_to_bundle_dir(),
        )
    except FunctionError as e:
        raise six.reraise(BundlingError, BundlingError(*e.args),
                          sys.exc_info()[2])

    stats = json.loads(output)

    if stats['errors']:
        raise BundlingError('{}\n\n{}'.format(config_file,
                                              '\n\n'.join(stats['errors'])))

    if stats['warnings']:
        warnings.warn(stats['warnings'], WebpackWarning)

    # Generate contextual information about the generated assets
    stats['urlsToAssets'] = {}
    path_to_bundle_dir = settings.get_path_to_bundle_dir()
    for asset, config_file in six.iteritems(stats['pathsToAssets']):
        if path_to_bundle_dir in config_file:
            rel_path = config_file[len(path_to_bundle_dir):]
            rel_url = pathname2url(rel_path)
            if rel_url.startswith('/'):
                rel_url = rel_url[1:]
            url = '{}{}/{}/{}'.format(settings.BUNDLE_URL, settings.OUTPUT_DIR,
                                      settings.BUNDLE_DIR, rel_url)
            stats['urlsToAssets'][asset] = url

    return WebpackBundle(stats)