### Set up local development environment
Source: https://github.com/inveniosoftware/pywebpack/blob/master/CONTRIBUTING.rst
Commands to create a virtual environment and install the package in editable mode with all dependencies.
```console
$ mkvirtualenv pywebpack
$ cd pywebpack/
$ pip install -e .[all]
```
--------------------------------
### Install PyWebpack via pip
Source: https://github.com/inveniosoftware/pywebpack/blob/master/INSTALL.rst
Use this command to install the package from the Python Package Index.
```console
$ pip install pywebpack
```
--------------------------------
### Discover Bundles from Entry Points
Source: https://context7.com/inveniosoftware/pywebpack/llms.txt
Dynamically loads bundles from installed Python packages by discovering entry points defined in setup.py or pyproject.toml. Ensure packages define 'webpack_bundles' entry points.
```python
from pywebpack import WebpackBundleProject, bundles_from_entry_point
# Discover bundles from installed packages via entry points
# Packages define entry points in setup.py/pyproject.toml:
# [project.entry-points.webpack_bundles]
# mymodule_css = "mymodule.bundles:css"
# mymodule_js = "mymodule.bundles:js"
project = WebpackBundleProject(
working_dir='./build',
project_template_dir='./buildconfig',
bundles=bundles_from_entry_point('webpack_bundles'), # Auto-discover
)
project.buildall()
```
--------------------------------
### Manage Webpack Projects with WebpackProject
Source: https://context7.com/inveniosoftware/pywebpack/llms.txt
Wraps an existing Webpack project to provide a Python API for npm commands like install and build.
```python
from pywebpack import WebpackProject
# Initialize project pointing to a directory with package.json
project = WebpackProject('./my-webpack-project')
# Install npm dependencies (runs npm install)
project.install()
# Run the build script defined in package.json (runs npm run build)
project.build()
# Or do both in one call
project.buildall()
# Run any custom npm script
project.run('test')
project.run('lint', '--fix')
```
--------------------------------
### Run project tests
Source: https://github.com/inveniosoftware/pywebpack/blob/master/CONTRIBUTING.rst
Execute the test suite to verify changes, check code style, and build documentation.
```console
$ ./run-tests.sh
```
--------------------------------
### Handle PyWebpack exceptions
Source: https://context7.com/inveniosoftware/pywebpack/llms.txt
Demonstrates catching specific exceptions related to manifest loading, rendering, build processes, and dependency conflicts.
```python
from pywebpack import (
ManifestLoader,
InvalidManifestError,
UnfinishedManifestError,
UnsupportedManifestError,
UnsupportedExtensionError,
WebpackProject
)
from pywebpack.errors import MergeConflictError
# Handle manifest errors
try:
manifest = ManifestLoader().load('./manifest.json')
except InvalidManifestError:
print("Manifest format is invalid")
except UnfinishedManifestError:
print("Webpack build is still in progress")
except UnsupportedManifestError:
print("Unknown manifest format")
# Handle rendering errors
try:
print(manifest.entry.render())
except UnsupportedExtensionError as e:
print(f"Cannot render file type: {e}")
# Handle build errors
project = WebpackProject('./my-project')
try:
project.buildall()
except RuntimeError as e:
print(f"Build failed: {e}")
# Handle dependency conflicts
try:
project.create()
except MergeConflictError as e:
print(f"Incompatible dependencies: {e}")
```
--------------------------------
### Create a development branch
Source: https://github.com/inveniosoftware/pywebpack/blob/master/CONTRIBUTING.rst
Create a new branch to isolate your changes.
```console
$ git checkout -b name-of-your-bugfix-or-feature
```
--------------------------------
### Clone the PyWebpack repository
Source: https://github.com/inveniosoftware/pywebpack/blob/master/CONTRIBUTING.rst
Use this command to create a local copy of your forked repository.
```console
$ git clone git@github.com:your_name_here/pywebpack.git
```
--------------------------------
### Create Projects from Templates with WebpackTemplateProject
Source: https://context7.com/inveniosoftware/pywebpack/llms.txt
Generates a Webpack project from a template directory and supports injecting configuration via static dictionaries or callables.
```python
from pywebpack import WebpackTemplateProject
# Create project from template with injected configuration
project = WebpackTemplateProject(
working_dir='./build', # Where files will be copied
project_template_dir='./buildconfig', # Template with package.json & webpack.config.js
config={'debug': True, 'publicPath': '/static/'}, # Injected config
config_path='build/config.json' # Where config.json will be written
)
# Create the project (copies template + writes config.json)
project.create()
# Install dependencies and build
project.buildall()
# Clean up the generated project
project.clean()
# Config can also be a callable for dynamic generation
project = WebpackTemplateProject(
working_dir='./build',
project_template_dir='./buildconfig',
config=lambda: {'timestamp': time.time(), 'entries': get_entries()}
)
```
--------------------------------
### Commit and push changes
Source: https://github.com/inveniosoftware/pywebpack/blob/master/CONTRIBUTING.rst
Stage, commit with a structured message, and push your changes to the remote repository.
```console
$ git add .
$ git commit -s
-m "component: title without verbs"
-m "* NEW Adds your new feature."
-m "* FIX Fixes an existing issue."
-m "* BETTER Improves and existing feature."
-m "* Changes something that should not be visible in release notes."
$ git push origin name-of-your-bugfix-or-feature
```
--------------------------------
### Configure Asset File Storage
Source: https://context7.com/inveniosoftware/pywebpack/llms.txt
Control how asset files are copied or linked during project creation. FileStorage copies files (default), while LinkStorage creates symlinks, which is faster for development. LinkStorage can also be configured with a depth to symlink directories.
```python
from pywebpack import WebpackTemplateProject, FileStorage, LinkStorage
# FileStorage (default) - copies files, skips if destination is newer
project = WebpackTemplateProject(
working_dir='./build',
project_template_dir='./template',
storage_cls=FileStorage # Default behavior
)
# LinkStorage - creates symlinks instead of copies (faster for development)
project = WebpackTemplateProject(
working_dir='./build',
project_template_dir='./template',
storage_cls=LinkStorage
)
# LinkStorage with depth control - symlink directories instead of individual files
from functools import partial
project = WebpackTemplateProject(
working_dir='./build',
project_template_dir='./template',
storage_cls=partial(LinkStorage, depth=1) # Symlink top-level dirs
)
project.create()
```
--------------------------------
### Render HTML Tags from ManifestEntry
Source: https://context7.com/inveniosoftware/pywebpack/llms.txt
Represents a single asset entry and can render appropriate HTML tags for inclusion in templates. Paths within an entry can be iterated over.
```python
from pywebpack import Manifest, ManifestEntry, ManifestLoader
# Create manifest manually
manifest = Manifest()
manifest.add(ManifestEntry('scripts', ['/static/app.abc123.js', '/static/vendor.def456.js']))
manifest.add(ManifestEntry('styles', ['/static/app.xyz789.css']))
# Render HTML tags
print(manifest.scripts.render())
# Output:
print(manifest.styles.render())
# Output:
# Use in templates (e.g., Jinja2)
# {{ manifest.scripts|safe }}
# Iterate over paths in an entry
for path in manifest.scripts:
print(path) # /static/app.abc123.js, /static/vendor.def456.js
```
--------------------------------
### Define Asset Bundles with WebpackBundle
Source: https://context7.com/inveniosoftware/pywebpack/llms.txt
Represents a collection of assets, entry points, dependencies, and aliases for a specific module.
```python
from pywebpack import WebpackBundle
# Define a bundle with entries, dependencies, and aliases
mainsite_bundle = WebpackBundle(
'./modules/mainsite/static', # Path to static assets
entry={
'mainsite-base': './js/mainsite-base.js',
'mainsite-products': './js/mainsite-products.js',
},
dependencies={
'jquery': '^3.6.0',
'bootstrap': '^5.2.0'
},
devDependencies={
'sass': '^1.50.0'
},
aliases={
'@mainsite': './js/mainsite'
},
copy=[
{'from': './images/', 'to': './dist/images/'}
]
)
# Define another bundle for a different module
backoffice_bundle = WebpackBundle(
'./modules/backoffice/static',
entry={
'backoffice-admin': './js/admin.js',
},
dependencies={
'jquery': '^3.5.0', # Will be resolved to ^3.6.0 (highest compatible)
'lodash': '~4.17.0'
}
)
```
--------------------------------
### Aggregate Bundles with WebpackBundleProject
Source: https://context7.com/inveniosoftware/pywebpack/llms.txt
Collects multiple bundles, merges their dependencies, and manages a unified Webpack build process.
```python
from pywebpack import WebpackBundleProject, WebpackBundle
# Create bundles
bundle1 = WebpackBundle(
'./modules/frontend/static',
entry={'frontend': './js/app.js'},
dependencies={'react': '^18.0.0'}
)
bundle2 = WebpackBundle(
'./modules/admin/static',
entry={'admin': './js/admin.js'},
dependencies={'react': '^18.0.0', 'lodash': '^4.17.0'}
)
# Create bundle project
project = WebpackBundleProject(
working_dir='./build',
project_template_dir='./buildconfig',
bundles=[bundle1, bundle2],
config={'mode': 'production'},
config_path='config.json',
allowed_copy_paths=['./build', './static'] # Security: restrict copy paths
)
# Access merged properties
print(project.entry) # {'frontend': './js/app.js', 'admin': './js/admin.js'}
print(project.dependencies) # Merged deps with version resolution
print(project.aliases) # Merged webpack aliases
# Build the project
project.create() # Copy templates, bundles, generate package.json & config.json
project.install() # npm install
project.build() # npm run build
```
--------------------------------
### Parse Specific Manifest Formats with Factories
Source: https://context7.com/inveniosoftware/pywebpack/llms.txt
Use specific factories to parse known manifest formats or to use custom Manifest/ManifestEntry classes. Supports webpack-manifest-plugin, webpack-yam-plugin, and webpack-bundle-tracker formats.
```python
from pywebpack import (
WebpackManifestFactory,
WebpackYamFactory,
WebpackBundleTrackerFactory,
Manifest,
ManifestEntry
)
# webpack-manifest-plugin format: {"entry": "hashed-filename"}
manifest = WebpackManifestFactory().load('./dist/manifest.json')
print(manifest['app']) # Access by original entry name
# webpack-yam-plugin format: {"status": "built", "files": {"entry": ["paths"]}}
manifest = WebpackYamFactory().load('./dist/manifest.json')
print(manifest.app)
# webpack-bundle-tracker format: {"status": "done", "chunks": {...}, "assets": {...}}
manifest = WebpackBundleTrackerFactory().load('./webpack-stats.json')
print(manifest['app.js'])
print(manifest['app.css'])
# Use custom Manifest/ManifestEntry classes
class MyManifestEntry(ManifestEntry):
def render(self):
# Custom rendering logic
return f'' + super().render()
factory = WebpackManifestFactory(entry_cls=MyManifestEntry)
manifest = factory.load('./dist/manifest.json')
```
--------------------------------
### Load Webpack Manifests Automatically
Source: https://context7.com/inveniosoftware/pywebpack/llms.txt
Automatically detects and parses manifest files from common webpack plugins like webpack-manifest-plugin, webpack-yam-plugin, or webpack-bundle-tracker. The manifest can be accessed using attribute or dictionary-style notation.
```python
from pywebpack import ManifestLoader
# Load manifest (auto-detects format)
manifest = ManifestLoader().load('./dist/manifest.json')
# Access entries by name (attribute or dict-style)
print(manifest.app) # ManifestEntry object
print(manifest['main.js']) # ManifestEntry object
# Iterate over all entries
for entry in manifest:
print(f"{entry.name}: {list(entry)}")
# Example manifest.json (webpack-manifest-plugin format):
# {"main.js": "main.75244bb780acd727.js", "styles.css": "styles.a1b2c3d4.css"}
```
--------------------------------
### Merge dependencies from multiple sources
Source: https://context7.com/inveniosoftware/pywebpack/llms.txt
Use merge_deps to combine dependency dictionaries. It handles version resolution and raises conflicts for incompatible major versions.
```python
computed = {
'dependencies': {'lodash': '^4.17.0'},
'devDependencies': {'webpack': '^5.0.0'}
}
incoming = {
'dependencies': {'lodash': '^4.17.21', 'axios': '^1.0.0'},
'devDependencies': {'webpack': '^5.70.0'}
}
result = merge_deps(computed, incoming)
print(result)
```
--------------------------------
### Merge npm Dependencies
Source: https://context7.com/inveniosoftware/pywebpack/llms.txt
The `merge_deps` helper merges npm dependencies, keeping the highest compatible version for each package. The `max_version` helper compares semantic versions.
```python
from pywebpack.helpers import merge_deps, max_version
# Compare semantic versions
print(max_version('1.0.0', '1.2.0')) # '1.2.0'
print(max_version('^2.0.0', '2.1.0')) # '2.1.0'
print(max_version('1.0.0-alpha', '1.0.0')) # '1.0.0' (release > pre-release)
```
--------------------------------
### Handle MergeConflictError for incompatible versions
Source: https://context7.com/inveniosoftware/pywebpack/llms.txt
Catch MergeConflictError when attempting to merge dependencies with incompatible major versions.
```python
from pywebpack.errors import MergeConflictError
try:
merge_deps(
{'dependencies': {'react': '^17.0.0'}},
{'dependencies': {'react': '^18.0.0'}}
)
except MergeConflictError as e:
print(f"Cannot merge: {e}")
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.