def _build_standalone_tag(module): """ Generate a RequireJS script tag for a standalone module. If the config has a 'devel_tag' attribute set to 'separate_tag', generate a separate tag type. """ module_section = require_settings.REQUIRE_STANDALONE_MODULES[module] relative_baseurl = module_section.get('relative_baseurl', '') entry_file_name = _get_standalone_entry_filename(module, module_section) relative_path = os.path.join(relative_baseurl, entry_file_name) module_url = staticfiles_storage.url(resolve_require_module(relative_path)) if not require_settings.REQUIRE_DEBUG: # Production mode, output the compiled script tag result = ( '<script type="text/javascript" src="{0}">' '</script>').format(module_url) return mark_safe(result) # Development mode generation below devel_tag = module_section.get('devel_tag', 'data_attr') require_url = staticfiles_storage.url( resolve_require_url(require_settings.REQUIRE_JS)) if devel_tag == 'separate_tag': # Separate script tag mode result = ( '<script type="text/javascript" src="{0}"></script>' '<script type="text/javascript" src="{1}"></script>').format( require_url, module_url) return mark_safe(result) # Data attribute mode (devel_tag == 'data_attr') result = ( '<script type="text/javascript" src="{0}" data-main="{1}">' '</script>').format(require_url, module_url) return mark_safe(result)
def _setup_if_standalone(self): if not require_settings.REQUIRE_STANDALONE_MODULES: return for _, value in require_settings.REQUIRE_STANDALONE_MODULES.items(): relative_baseurl = value.get("relative_baseurl", "") almond_path = os.path.join(relative_baseurl, "almond.js") shutil.copyfile(self.env.resource_path("almond.js"), self.env.compile_dir_path(almond_path)) self.exclude_names.append(resolve_require_url(almond_path))
def require_module(module): """ Generates a dumped dictionary representation of a require module appropriate for embedding in a javascript template If the module is configured in REQUIRE_STANDALONE_MODULES, and REQUIRE_DEBUG is False, then then the standalone built version of the module will be loaded instead, bypassing require.js for extra load performance. This is adapted from the corresponding template tag in django-require, which is available under the following license: Copyright (c) 2009, David Hall. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of David Hall nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ if not require_settings.REQUIRE_DEBUG and module in require_settings.REQUIRE_STANDALONE_MODULES: return """{{src: '{module}' }}""".format(module=get_site_url( staticfiles_storage.url( resolve_require_module( require_settings.REQUIRE_STANDALONE_MODULES[module] ["out"]))), ) return """{{src: '{src}', "data-main": '{module}' }}""".format( src=get_site_url( staticfiles_storage.url( resolve_require_url(require_settings.REQUIRE_JS))), module=get_site_url( staticfiles_storage.url(resolve_require_module(module))), )
def require_module(module): """ Generates a dumped dictionary representation of a require module appropriate for embedding in a javascript template If the module is configured in REQUIRE_STANDALONE_MODULES, and REQUIRE_DEBUG is False, then then the standalone built version of the module will be loaded instead, bypassing require.js for extra load performance. This is adapted from the corresponding template tag in django-require, which is available under the following license: Copyright (c) 2009, David Hall. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of David Hall nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ if not require_settings.REQUIRE_DEBUG and module in require_settings.REQUIRE_STANDALONE_MODULES: return """{{src: '{module}' }}""".format( module = get_site_url(staticfiles_storage.url(resolve_require_module(require_settings.REQUIRE_STANDALONE_MODULES[module]["out"]))), ) return """{{src: '{src}', "data-main": '{module}' }}""".format( src = get_site_url(staticfiles_storage.url(resolve_require_url(require_settings.REQUIRE_JS))), module = get_site_url(staticfiles_storage.url(resolve_require_module(module))), )
def require_module(module): """ Inserts a script tag to load the named module, which is relative to the REQUIRE_BASE_URL setting. If the module is configured in REQUIRE_STANDALONE_MODULES, and REQUIRE_DEBUG is False, then then the standalone built version of the module will be loaded instead, bypassing require.js for extra load performance. """ if not require_settings.REQUIRE_DEBUG and module in require_settings.REQUIRE_STANDALONE_MODULES: return format_html('<script src="{}"></script>', staticfiles_storage.url(resolve_require_module(require_settings.REQUIRE_STANDALONE_MODULES[module]["out"])), ) return format_html('<script src="{}" data-main="{}"></script>', staticfiles_storage.url(resolve_require_url(require_settings.REQUIRE_JS)), staticfiles_storage.url(resolve_require_module(module)), )
def require_module(module): """ Inserts a script tag to load the named module, which is relative to the REQUIRE_BASE_URL setting. If the module is configured in REQUIRE_STANDALONE_MODULES, and REQUIRE_DEBUG is False, then then the standalone built version of the module will be loaded instead, bypassing require.js for extra load performance. """ if not require_settings.REQUIRE_DEBUG and module in require_settings.REQUIRE_STANDALONE_MODULES: return u"""<script src="{module}"></script>""".format( module = staticfiles_storage.url(resolve_require_module(require_settings.REQUIRE_STANDALONE_MODULES[module]["out"])), ) return u"""<script src="{src}" data-main="{module}"></script>""".format( src = staticfiles_storage.url(resolve_require_url(require_settings.REQUIRE_JS)), module = staticfiles_storage.url(resolve_require_module(module)), )
def require_custom(module, script=''): """ Inserts a script tag to load the named module, which is relative to the REQUIRE_BASE_URL setting. If the module is configured in REQUIRE_STANDALONE_MODULES, and REQUIRE_DEBUG is False, then then the standalone built version of the module will be loaded instead, bypassing require.js for extra load performance. """ if not require_settings.REQUIRE_DEBUG and module in require_settings.REQUIRE_STANDALONE_MODULES: result = """<script src="{module}"></script>""".format( module = staticfiles_storage.url(resolve_require_module(require_settings.REQUIRE_STANDALONE_MODULES[module]["out"])), ) else: result = """<script src="{src}" data-main="{module}"></script>""".format( src = staticfiles_storage.url(resolve_require_url(require_settings.REQUIRE_JS)), module = staticfiles_storage.url(resolve_require_module(module)), ) if script != '': result = """{result}<script>{script}</script>""".format(result=result,script=script) return result
def require_module(module): """ Inserts a script tag to load the named module, which is relative to the REQUIRE_BASE_URL setting. If the module is configured in REQUIRE_STANDALONE_MODULES, then the standalone built version of the module will be loaded instead, bypassing require.js for extra load performance. """ if module in require_settings.REQUIRE_STANDALONE_MODULES: return _build_standalone_tag(module) # Non-standalone mode result = ( '<script type="text/javascript" src="{src}" data-main="{module}">' '</script>').format( src=staticfiles_storage.url( resolve_require_url(require_settings.REQUIRE_JS)), module=staticfiles_storage.url(resolve_require_module(module)), ) return mark_safe(result)
def post_process(self, paths, dry_run=False, verbosity=1, **options): # If this is a dry run, give up now! if dry_run: return # Compile in a temporary environment. with TemporaryCompileEnvironment(verbosity=verbosity) as env: exclude_names = list(require_settings.REQUIRE_EXCLUDE) compile_info = {} # Copy all assets into the compile dir. for name, storage_details in paths.items(): storage, path = storage_details dst_path = os.path.join(env.compile_dir, name) dst_dir = os.path.dirname(dst_path) if not os.path.exists(dst_dir): os.makedirs(dst_dir) # Copy and generate md5 hash = hashlib.md5() with closing(storage.open(path, "rb")) as src_handle: with open(dst_path, "wb") as dst_handle: for block in self._file_iter(src_handle): hash.update(block) dst_handle.write(block) # Store details of file. compile_info[name] = hash.digest() # Run the optimizer. if require_settings.REQUIRE_BUILD_PROFILE is not False: if require_settings.REQUIRE_BUILD_PROFILE is not None: app_build_js_path = env.compile_dir_path(require_settings.REQUIRE_BUILD_PROFILE) else: app_build_js_path = env.resource_path("app.build.js") env.run_optimizer( app_build_js_path, dir = env.build_dir, appDir = env.compile_dir, baseUrl = require_settings.REQUIRE_BASE_URL, ) # Compile standalone modules. if require_settings.REQUIRE_STANDALONE_MODULES: shutil.copyfile( env.resource_path("almond.js"), env.compile_dir_path("almond.js"), ) exclude_names.append(resolve_require_url("almond.js")) for standalone_module, standalone_config in require_settings.REQUIRE_STANDALONE_MODULES.items(): if "out" in standalone_config: if "build_profile" in standalone_config: module_build_js_path = env.compile_dir_path(standalone_config["build_profile"]) else: module_build_js_path = env.resource_path("module.build.js") env.run_optimizer( module_build_js_path, name = "almond", include = standalone_module, out = env.build_dir_path(standalone_config["out"]), baseUrl = os.path.join(env.compile_dir, require_settings.REQUIRE_BASE_URL), ) else: raise ImproperlyConfigured("No 'out' option specified for module '{module}' in REQUIRE_STANDALONE_MODULES setting.".format( module = standalone_module )) # Update assets with modified ones. compiled_storage = FileSystemStorage(env.build_dir) # Walk the compiled directory, checking for modified assets. for build_dirpath, _, build_filenames in os.walk(env.build_dir): build_dirpath = force_text(build_dirpath) for build_filename in build_filenames: build_filename = force_text(build_filename) # Determine asset name. build_filepath = os.path.join(build_dirpath, build_filename) build_name = build_filepath[len(env.build_dir)+1:] build_storage_name = build_name.replace(os.sep, "/") # Ignore certain files. if build_storage_name in exclude_names: # Delete from storage, if originally present. if build_name in compile_info: del paths[build_name] self.delete(build_storage_name) continue # Update the asset. with File(open(build_filepath, "rb"), build_storage_name) as build_handle: # Calculate asset hash. hash = hashlib.md5() for block in self._file_iter(build_handle): hash.update(block) build_handle.seek(0) # Check if the asset has been modifed. if build_name in compile_info: # Get the hash of the new file. if hash.digest() == compile_info[build_name]: continue # If we're here, then the asset has been modified by the build script! Time to re-save it! paths[build_name] = (compiled_storage, build_name) # It's definitely time to save this file. self.delete(build_storage_name) self.save(build_storage_name, build_handle) # Report on the modified asset. yield build_name, build_name, True # Report on modified assets. super_class = super(OptimizedFilesMixin, self) if hasattr(super_class, "post_process"): for path in super_class.post_process(paths, dry_run, **options): yield path
def require_module(module, mode=None): """ Inserts a script tag to load the named module, which is relative to the REQUIRE_BASE_URL setting. If the module is configured in REQUIRE_STANDALONE_MODULES, and REQUIRE_DEBUG is False, then then the standalone built version of the module will be loaded instead, bypassing require.js for extra load performance. If your require.config uses shimed modules, set mode='shim'. - If the module is configured in REQUIRE_COMMON_MODULE, and REQUIRE_DEBUG is False, then then the common module will be loaded with requirejs embedded, bypassing an additional load of require.js for extra load performance. - If the specified module does not match REQUIRE_COMMON_MODULE and REQUIRE_DEBUG is False a script tag will be inserted requireing the specified module. If REQUIRE_DEBUG is True, a script tag will be inserted requireing the common module with a nested require call of the specified module. """ if not require_settings.REQUIRE_DEBUG: if module in require_settings.REQUIRE_STANDALONE_MODULES: string = u"""<script src="{module}"></script>""".format( module = staticfiles_storage.url(resolve_require_module(require_settings.REQUIRE_STANDALONE_MODULES[module]["out"]))) elif module in require_settings.REQUIRE_COMMON_MODULE: # Load common (Assume requirejs is included with common) string = u"""<script src="{common}"></script>""".format( common = staticfiles_storage.url(resolve_require_module(require_settings.REQUIRE_COMMON_MODULE[module]["out"]))) else: # Load additional modules (Assume that requirejs is accessible) string = u"""<script>require(['{module}']);</script>""".format( module = resolve_require_module_hash(module)) return string elif require_settings.REQUIRE_COMMON_MODULE: common_keys = require_settings.REQUIRE_COMMON_MODULE.keys() common_module = common_keys[0] # The specified module is the common module if module in require_settings.REQUIRE_COMMON_MODULE: if mode == 'shim': # Requirejs and shim common module string = u"""<script src="{requirejs}"></script>""".format( requirejs = staticfiles_storage.url(resolve_require_url(require_settings.REQUIRE_JS))) string += u"""<script>require(['{common}']);</script>""".format( common = staticfiles_storage.url(resolve_require_module(common_module))) else: # Requirejs and data-main common module string = u"""<script src="{requirejs}" data-main="{common}"></script>""".format( requirejs = staticfiles_storage.url(resolve_require_url(require_settings.REQUIRE_JS)), common = staticfiles_storage.url(resolve_require_module(common_module))) # The specified module is not the common module (assume common has already been loaded) elif mode == 'shim': # Require common and nest a require for the specified module string = u"""<script>require(['{common}'], function () {{""".format( common = staticfiles_storage.url(resolve_require_module(common_module))) string += u"""require(['{module}']);""".format( module = resolve_require_module_hash(module)) string += u"""});</script>""" # Non shim mode template inheritance else: # Just require the specified module string = u"""<script>require(['{module}']);</script>""".format( module = resolve_require_module_hash(module)) return string return u"""<script src="{src}" data-main="{module}"></script>""".format( src = staticfiles_storage.url(resolve_require_url(require_settings.REQUIRE_JS)), module = staticfiles_storage.url(resolve_require_module(module)), )