Git Product home page Git Product logo

django-compressor-parceljs's Introduction

https://static.pepy.tech/personalized-badge/django-compressor-parceljs?period=total&units=international_system&left_color=black&right_color=green&left_text=Downloads

Django Compressor Parceljs

django-compressor-parceljs is base on Django-Compressor. It provides additional support to bundles and minifies your typescript, vue, react, scss etc, in a Django template into cacheable static files using parceljs.

For more information on how django-compressor-parceljs really works visit Django-Compressor

Quickstart

Install django-compress:

pip install django-compressor-parceljs

Install parcel-bundler:

npm install -g parcel

Add it to your INSTALLED_APPS:

INSTALLED_APPS = (
    ...
    'compressor',
    ...
)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    # other finders..
    'compressor.finders.CompressorFinder',
)

Other Configurations

To minify your code for production, you need to set COMPRESS_ENABLED and COMPRESS_OFFLINE to true in settings.py.

From django-compressor settings, the value of COMPRESS_ENABLED = !DEBUG, in settings.py.

COMPRESS_ENABLED = True
COMPRESS_OFFLINE = True
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

Then run,

python manage.py compress --setting path-to-your-production-settings

For more information on django-compressor-settings

Usage

In your template, load compress {% load compress %} then use {% compress parcel %} <script> {% endcompress %} to load a script. for example:

{% load static %}
{% load compress %}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Vue Django Testing</title>
  </head>
  <body>
    ....
   {% compress parcel file myts %}
    <script src="{% static 'js/index.ts' %}"></script>
   {% endcompress %}
  </body>
  ...

Private directories

You can use other directories in your project which are not marked as static files with django-compressor-parceljs.

This feature was added to avoid exposing your real code structure, like your front-end components source, to the real world via static urls.

Django-compressor-parceljs provides another tag {% private_static %} which works like the normal django static tag {% static %} to enable you work with a seperate directory registered in COMPRESS_PRIVATE_DIRS in settings.py. And they won't be accessed via any url.

Private directory setup

settings.py
COMPRESS_PRIVATE_DIRS = [
  os.path.join(BASE_DIR, 'my_dir'),
  ....
]
some_file.html
{% load static %}
{% load compress %}
{% load private_static %}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Vue Django Testing</title>
  </head>
  <body>
    ....
   {% compress parcel file myts %}
    <script src="{% private_static 'js/index.js' %}"></script>
   {% endcompress %}
  </body>
  ...

Vue example

Create a vue project in your django project root. See the demo project django_vue or with react

npm init --yes
npm install -D vue-template-compiler @vue/component-compiler-utils
npm install vue

In your django project app create

static/components/test.vue
static/js/index.js

In static/components/test.vue,

<template>
  <div>
    <h1>{{ message }}</h1>
  </div>
</template>

<script>
    export default {
      name: "app",
      components: {},
      data: {
        message: "Hello Vue",
      },
      computed: {}
    };
    </script>

<style lang="scss">
</style>

In static/js/index.js,

import Vue from "vue";
import test  from "../components/test.vue";
new Vue(test).$mount("#components-demo");

In your django template,

{% load static %}
{% load compress %}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Vue Django Testing</title>
  </head>
  <body>
    ....
   <div id="components-demo"></div>
   {% compress parcel file myjs %}
     <script src="{% static 'js/index.js' %}"></script>
   {% endcompress %}
  </body>
  ...

Run runserver

python manage.py runserver

You have successfully bundled your vue app into your django template.

Using Parceljs to bundle SASS, SCSS, LESS

Integrating compilers into django-compressor is quiet very easy. All you need is to provide a COMPRESS_PRECOMPILERS option in django settings.py. For more information visit django-compressor precompilers

COMPRESS_PRECOMPILERS = (
    ('text/coffeescript', 'coffee --compile --stdio'),
    ('text/less', 'lessc {infile} {outfile}'),
    ('text/x-sass', 'sass {infile} {outfile}'),
    ('text/x-scss', 'sass --scss {infile} {outfile}'),
    ('text/stylus', 'stylus < {infile} > {outfile}'),
    ('text/foobar', 'path.to.MyPrecompilerFilter'),
)

Use compressor.filters.parceljs.ParserFilterCSS on scss, sass or less in COMPRESS_PRECOMPILERS options as filter. For example:

COMPRESS_PRECOMPILERS = (
    # ('text/coffeescript', 'coffee --compile --stdio'),
    ('text/less', 'compressor.filters.parceljs.ParserFilterCSS'),
    # ('text/x-sass', 'sass {infile} {outfile}'),
    ('text/x-scss', 'compressor.filters.parceljs.ParserFilterCSS'),
    # ('text/stylus', 'stylus < {infile} > {outfile}'),
    # ('text/foobar', 'path.to.MyPrecompilerFilter'),
)

In your template,

{% load static %}
{% load compress %}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Vue Django Testing</title>
    {% compress css file style %}
        <link rel="stylesheet" type="text/x-scss"  href="{% static 'css/style.scss'%}">
    {% endcompress %}
  </head>
  <body>
  .......

Add the type="text/x-scss" for django-compressor to use the precompiler options to compile the asset.

There is alittle drawback with parceljs css url resolver. There is no configuration for parceljs to ignore resolving css url since django will always resolve static urls automatically. Read more this issue

A solution is to use ///.. on the url path followed by /static/(path_to_file)

body{
    background-color: lightblue;
    background-image: url(///../static/img/ssd/avatar1.png);

    button{
        font-size: .8rem;
    }
}

Using typescript directly in django template

Add lang attribute to the script tag <script lang="ts"></script>

npm init --yes
npm install -D @babel/core, @babel/preset-env, typescript
{% load static %}
{% load compress %}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Vue Django Testing</title>
  </head>
  <body>
    ....
   {% compress parcel file myts %}
     <script lang="ts">
        interface IUser {
            name: string,
            age: number
        }

        class User implements IUser{
            constructor(user:IUser){
                this.name = user.name
                this.age = user.age
            }
            name: string
            age: number

            get_name = () => {
                return this.name
            };
        }

        const Peter = new User({name:'Peter', age:32})
        console.log(Peter)
     </script>
   {% endcompress %}
  </body>
  ...

django-compressor-parceljs's People

Contributors

dependabot[bot] avatar e8johan avatar eadwincode avatar jezeniel avatar nerdoc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

django-compressor-parceljs's Issues

Getting Error When Using with Typescript

I believe I have everything installed and configured correctly.

STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", "compressor.finders.CompressorFinder", ]

COMPRESS_ENABLED = True

COMPRESS_REBUILD_TIMEOUT = 2592000  # (30 days in seconds)
COMPRESS_OFFLINE = False

COMPRESS_OFFLINE_TIMEOUT = 31536000  # (1 year in seconds)
COMPRESS_OUTPUT_DIR = 'dev'

And in my template:

{% block extra_js %}
    <script type="text/javascript" src="{% static 'bundle.js' %}"></script>
    {% compress parcel file myts %}
        <script src="{% static 'test.ts' %}"></script>
   {% endcompress %}
 {% endblock %}

However, when I hit the page I get the following error:

TypeError at /todo/
Signal.__init__() got an unexpected keyword argument 'providing_args'

Any idea what could be wrong?

unknown option '--no-minify'

Hello
I have the package as described in the ReadMe.md file. Unfortunately I get the error unknown option '--no-minify' when calling my Django page.
in the file <<project path>>/venv/lib/python3.8/site-packages/compressor/filters/parceljs.py line 86, in input
Did I do something wrong?

My Python Version is 3.8.5
Django Version: 3.1.3
Parcel Version: [email protected]

Parcel problem when trying to manage.py compress

When following the instructions to install Parcel, it installs Parcel v2, which seems not not have the same command line arguments that Parcel v1 used. I ran into this when trying to get the "typescript directly in my django templates" example working.

You can fix this by installing parcel-bundler instead. which I guess is also known as parcel v1.

The error message that comes up when trying to use this with just parcel is:
CommandError: An error occurred during rendering /Users/me/Desktop/code_testing/typescript/django_typescript/home/templates/home/index.html: error: unknown option '-d'

To fix this, I did:
sudo npm uninstall -g parcel
sudo npm install -g parcel-bundler

Edit: By the way I love this package, i'm just digging into Typescript and this is the first way that makes sense to me on how to get that working in django where my ts code is in my django templates!

image references from Vue components

When creating an img element in a Vue template, I run into two alternative scenarios:

  • If I specify an absolute path, e.g. '/static/images/foo.png', parcel complains that the directory does not exist.
  • If I specify a relative path, e.g. '../images/foo.png', parcel decides to compress the png to a different filename, e.g. '/foo.4055feba.png', but does not create the file in the compressed output directory.

I've also tried the '///../static/images/foo.png' trick mentioned in the css section, but to no avail (the browser simply does not load the '///../static/' png.

How do I refer to a png from a Vue component in a file.

STATIC_ROOT / COMPRESS_ROOT missing in Readme.md

Hi, I just try to get a Vue example running, without success by now.
Just one thing: STATIC_ROOT / COMPRESS_ROOT has to be set, else ./manage.py compress complains. Could you add that to your readme, like

STATIC_ROOT = BASEDIR / "static"

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.