Skip to content

Commit

Permalink
Add script tag support (#16)
Browse files Browse the repository at this point in the history
* added script tag support

* added use_contao_template_variables option

* huge documentation update
  • Loading branch information
koertho authored Feb 11, 2021
1 parent d75963b commit b2ca1b0
Show file tree
Hide file tree
Showing 12 changed files with 348 additions and 256 deletions.
47 changes: 38 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@
![CI](https://github.com/heimrichhannot/contao-encore-bundle/workflows/CI/badge.svg)
[![Coverage Status](https://coveralls.io/repos/github/heimrichhannot/contao-encore-bundle/badge.svg?branch=master)](https://coveralls.io/github/heimrichhannot/contao-encore-bundle?branch=master)

This bundle brings deep integration for symfony encore into contao. On the one hand, your can prepare your bundles to define own webpack entries, which added with just one command to your webpack entries. On the other hand, this bundle allows you to add encore entries only on the pages you need them for optimizing your website performance.
Use the power and simplicity of symfony webpack encore in contao. This bundle let you decide on layout and page level, which encore entries should be loaded. If you want more, you can prepare your bundles define their own encore entries, so never need to manually add or remove encore entries again.

## Features
- use symfony encore ([symfony/webpack-encore](https://github.com/symfony/webpack-encore) and [symfony/webpack-encore-bundle](https://github.com/symfony/webpack-encore-bundle)) to enhance your contao assets workflow
- conditionally load your assets only if necessary (entrypoints can be activated in the backend in layout and page setting or added via service from your bundle code (e.g. in a frontend module))
- prepare your bundles to add encore entries when install them and strip assets from the contao global asset arrays

## Setup

## Setup


### Prerequisites

Expand All @@ -21,6 +23,7 @@ This bundle brings deep integration for symfony encore into contao. On the one h

* In order to add the node dependencies required by composer bundles, you probably want to add them to your project's node dependencies when running webpack in the project's scope. You can use [Foxy](docs/introductions/bundles_with_webpack.md) for this task.


### Prepare your project and bundle

Setup your project for encore bundle:
Expand All @@ -30,26 +33,30 @@ Setup your project for encore bundle:
[Bundle setup](docs/setup_bundle.md)


### Run Encore

1. Clear your cache

php vendor/bin/contao-console cache:clear

### Run Encore
1. Run encore prepare command

1. Clear your cache (`vendor/bin/contao-console cache:clear`)
php vendor/bin/contao-console encore:prepare

1. Run the Contao command `vendor/bin/contao-console encore:prepare`. This generates a file called `encore.bundles.js` in your project root.
This file contains entries for all contao encore compatible bundles that are added by calling `encoreBundles.addEntries();` in your `webpack.config.js`.
1. Run encore to generate the assets

`yarn encore dev`

> IMPORTANT: You have to call this command every time you want your bundle webpack entries to be updated, e.g. if you added new entries to your yml configuration or added a new encore-bundle compatible bundle.
1. Activate encore entries in the contao backend

1. Now run `yarn encore dev --watch` to generate the assets. For production assets (deployment), run `yarn encore production`.
Now run `yarn encore dev --watch` to generate the assets. For production assets (deployment), run `yarn encore production`.

* If you have a large set of entries and the generation takes very long, you can use the command line parameter `--entries` in order to limit the generation to certain entries: `yarn encore dev --entries="entry1,entry2,entry3"` (the entry names can be taken from the generated file `encore.bundles.js`).
* You can also explicitly skip certain entries for generation by using the command line parameter `--skip-entries`: `yarn encore dev --skip-entries="entry1,entry2,entry3"`.

1. If the generation succeeded without errors, you can now active encore entries. See Usage -> Activate encore entries for how to do that.



## Usage

### Activate encore entries
Expand All @@ -62,6 +69,28 @@ This file contains entries for all contao encore compatible bundles that are add
* Pay attention that you check entries as active (if you want them to be loaded)!
* If you want an already added entry to be not loaded on an specific page, select it as entry and don't check "active".

### Prepare command

php vendor/bin/contao-console encore:prepare

The prepare command must be executed after every change to the encore entries configuration, e.g. after a composer update or changes to that configurations in your own code.

This generates a file called `encore.bundles.js` in your project root.
This file contains entries for all contao encore compatible bundles that are added by calling `encoreBundles.addEntries();` in your `webpack.config.js`.

### Run encore

Run encore to generate/compile your assets.

yarn encore dev
yarn encore dev --watch
yarn encore prod

This bundle adds to additional options to the encore command:

* `entries`: Limit generation to passed entries. Useful if you have a large amount of entries and compilation needs time, but you're working on a specific entries. Example: `yarn encore dev --entries="entry1,entry2,entry3"`
* `skip-entries`: Skip given entries for generation. Example: `yarn encore dev --skip-entries="entry1,entry2,entry3"`

## Documentation

[Project setup](docs/setup_project.md) - Prepare your contao project for use with encore and encore bundle
Expand Down
65 changes: 34 additions & 31 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,49 +6,52 @@ The complete bundle configuration:
# Default configuration for extension with alias: "huh_encore"
huh_encore:

# Add javascript files which should be registered as encore entries.
js_entries:
# Use contao template variables in fe_page (stylesheets, head, mootools) for inserting assets instead of the custom template variables of this bundle. Recommended: true. Default: false (due bc reasons). Will be default true in next major version.
use_contao_template_variables: false

# Prototype
-
# Add javascript files which should be registered as encore entries.
js_entries:

# Will be shown in contao backend and will be used as alias/identifier in the database.
name: ~ # Required
# Prototype
-

# Path to the Javascript file.
file: ~ # Required
# Will be shown in contao backend and will be used as alias/identifier in the database.
name: ~ # Required

# Set to true, if entry requires css.
requires_css: ~
# Path to the Javascript file.
file: ~ # Required

# Set to true, if entry should added to the encoreHeadScripts section in your page layout instead to the bottom (CSS will always be added to the head).
head: ~
templates:
# Set to true, if entry requires css.
requires_css: ~

# Register import templates to customize how assets are imported into your templates.
imports:
# Set to true, if entry should added to the encoreHeadScripts section in your page layout instead to the bottom (CSS will always be added to the head).
head: ~
templates:

# Prototype
-
# Register import templates to customize how assets are imported into your templates.
imports:

# Unique template alias. Example: default_css
name: ~ # Required
# Prototype
-

# Full references twig template path. Example: @HeimrichHannotContaoEncore/encore_css_imports.html.twig
template: ~ # Required
# Unique template alias. Example: default_css
name: ~ # Required

# A list of keys that should be stripped from the global contao arrays. Here you can add assets, that you serve with webpack, so they won't be loaded twice or on the wrong page. IMPORTANT: The strings defined here must match the array keys in Contao's global arrays
unset_global_keys:
# Full references twig template path. Example: @HeimrichHannotContaoEncore/encore_css_imports.html.twig
template: ~ # Required

# Assets will be stripped from $GLOBALS['TL_JAVASCRIPT']
js: []
# A list of keys that should be stripped from the global contao arrays. Here you can add assets, that you serve with webpack, so they won't be loaded twice or on the wrong page. IMPORTANT: The strings defined here must match the array keys in Contao's global arrays
unset_global_keys:

# Assets will be stripped from $GLOBALS['TL_JQUERY']
jquery: []
# Assets will be stripped from $GLOBALS['TL_JAVASCRIPT']
js: []

# Assets will be stripped from $GLOBALS['TL_USER_CSS'] and $GLOBALS['TL_CSS']
css: []
# Assets will be stripped from $GLOBALS['TL_JQUERY']
jquery: []

# Remove jQuery from global array, if addJQuery is enabled in layout section.
unset_jquery: false
# Assets will be stripped from $GLOBALS['TL_USER_CSS'] and $GLOBALS['TL_CSS']
css: []

# Remove jQuery from global array, if addJQuery is enabled in layout section.
unset_jquery: false
```
19 changes: 10 additions & 9 deletions docs/setup_bundle.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,14 @@ With encore bundle you can prepare your bundles to automatically create encore e
```yaml
huh_encore:
js_entries:
- { name: contao-my-project-bundle, requires_css: true, head: false, file: "vendor/acme/contao-my-project-bundle/src/Resources/public/js/my-project-bundle.js" }
- { name: special-feature, requires_css: true, head: false, file: "vendor/acme/contao-my-project-bundle/src/Resources/public/js/awesome-but-rare-used-feature.js" }
- name: contao-my-project-bundle
requires_css: true
head: false
file: "vendor/acme/contao-my-project-bundle/src/Resources/public/js/my-project-bundle.js"
- name: special-feature
requires_css: true
head: false
file: "vendor/acme/contao-my-project-bundle/src/Resources/public/js/awesome-but-rare-used-feature.js"
unset_global_keys:
js:
- contao-my-project-bundle
Expand Down Expand Up @@ -51,12 +57,7 @@ With encore bundle you can prepare your bundles to automatically create encore e

> If you want encore bundle to be an optional dependency, please consider the [developers documentation](developers.md).

1. You probably want to have your bundle's node dependencies added automatically to the project's node_modules directory when installed. You can simply use [Foxy](https://github.com/fxpio/foxy) for this task. To keep it simple: besides having foxy installed in your project, you need to set `"foxy": true` in the `extra` section of your bundle's `composer.json` and add an ordinary `package.json` as usual for node modules. See [heimrichhannot/contao-list-bundle](https://github.com/heimrichhannot/contao-list-bundle) for an example.
1. Optional: You probably want to have your bundle's node dependencies added automatically to the project's node_modules directory when installed. You can simply use [Foxy](https://github.com/fxpio/foxy) for this task. To keep it simple: besides having foxy installed in your project, you need to set `"foxy": true` in the `extra` section of your bundle's `composer.json` and add an ordinary `package.json` as usual for node modules. See [heimrichhannot/contao-list-bundle](https://github.com/heimrichhannot/contao-list-bundle) for an example.

1. Optional: Add encore entries automatically from code (for example in frontend module):
1. Optional: If your bundle need an encore entry to be loaded to work (e.g. if it's needed for a frontend module or widget), you can load entries from you code. See [developers documentation](developers.md) for how to do that.

```php
if ($this->container->has('huh.encore.asset.frontend')) {
$this->container->get('huh.encore.asset.frontend')->addActiveEntrypoint('contao-slick-bundle');
}
```
5 changes: 5 additions & 0 deletions docs/setup_entries.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Setup entries

This guide tells you how to add encore entries from you code.

1. Create javascript file per entry, like
107 changes: 54 additions & 53 deletions docs/setup_project.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Setup your project for encore bundle.

1. Update your database

1. Create your webpack/encore config file (`webpack.config.js`) in your project root.
1. Update/Create your webpack config file (`webpack.config.js`) in your project root.

1. Require the generated `encore.bundles.js` (this file is generated with the encore:prepare command, see [Run Encore](../README.md#run-encore))

Expand All @@ -19,59 +19,60 @@ Setup your project for encore bundle.
```

1. Call `encoreBundles.addEntries()`

Example:

```javascript
let Encore = require('@symfony/webpack-encore'),
encoreBundles = require('./encore.bundles');
Encore
.setOutputPath('web/build/')
.setPublicPath('/build')
.cleanupOutputBeforeBuild()
.enableVersioning()
// css
.enableSassLoader()
.enablePostCssLoader()
// js
.enableSourceMaps(!Encore.isProduction())
.splitEntryChunks()
.enableSingleRuntimeChunk()
;
// this function adds entries for all contao encore compatible bundles automatically
// -> the source of that is the file "encore.bundles.js" in your project root which is
// generated automatically using the contao command "vendor/bin/contao-console encore:prepare"
// -> you can pass an array to the function if you want to skip certain entries
encoreBundles.addEntries();
// support dynamic chunks
let config = Encore.getWebpackConfig();
config.output.chunkFilename = '[name].bundle.js';
// support symlinks
config.resolve.symlinks = false;

Example:

```javascript
// webpack.config.js
let Encore = require('@symfony/webpack-encore'),
encoreBundles = require('./encore.bundles');
Encore
.setOutputPath('web/build/')
.setPublicPath('/build')
.cleanupOutputBeforeBuild()
.enableVersioning()
// css
.enableSassLoader()
.enablePostCssLoader()
// js
.enableSourceMaps(!Encore.isProduction())
module.exports = config;
```
.splitEntryChunks()
.enableSingleRuntimeChunk()
;
// this function adds entries for all contao encore compatible bundles automatically
// -> the source of that is the file "encore.bundles.js" in your project root which is
// generated automatically using the contao command "vendor/bin/contao-console encore:prepare"
// -> you can pass an array to the function if you want to skip certain entries
encoreBundles.addEntries();
// support dynamic chunks
let config = Encore.getWebpackConfig();
// support symlinks
config.resolve.symlinks = false;
module.exports = config;
```

We recommend adding corejs polyfill (former babel polyfill) into your setup, see [Javascript setup section](setup_javascript.md) for more informations.
> We recommend adding corejs polyfill (former babel polyfill) into your setup, see [Javascript setup section](setup_javascript.md) for more informations.

1. Update your `fe_page` template or use the bundled `fe_page_encore_bundle` template. Following changes to your template are necessary:
1. Add the following in `<head>` region:
1. Set `huh_encore.use_contao_template_variables` to true

```php
<?= $this->encoreStylesheets; ?>
<?= $this->encoreHeadScripts; ?>
```

1. Add the following into the footer region:

```php
<?= $this->encoreScripts; ?>
`````
```yaml
# config/config.yml (Contao >= 4.9)
# app/config/config.yml (Contao 4.4)
huh_encore:
use_contao_template_variables: true
```

> This option was added to use the default contao fe_page template variables instead of custom variables from this bundle. The old implementation is considered deprecated and will be removed in a future version. If you still want or need to use it, see `src/Resources/contao/templates/fe_page_encore_bundle.html5` for usage.

1. Optional: Add entries.
You can now add entries from your project, if you maintain your assets in your project code. The easiest way would be to just add them in your webpack.config.js. But you can also add them from configuration, see [Bundle Setup](setup_bundle.md) for more information.
6 changes: 5 additions & 1 deletion src/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?php

/*
* Copyright (c) 2020 Heimrich & Hannot GmbH
* Copyright (c) 2021 Heimrich & Hannot GmbH
*
* @license LGPL-3.0-or-later
*/
Expand All @@ -21,6 +21,10 @@ public function getConfigTreeBuilder()

$rootNode
->children()
->booleanNode('use_contao_template_variables')
->defaultFalse()
->info('Use contao template variables in fe_page (stylesheets, head, mootools) for inserting assets instead of the custom template variables of this bundle. Recommended: true. Default: false (due bc reasons). Will be default true in next major version.')
->end()
->arrayNode('js_entries')
->info('Add javascript files which should be registered as encore entries.')
->arrayPrototype()
Expand Down
14 changes: 13 additions & 1 deletion src/EventListener/GeneratePageListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,9 @@ public function __invoke(PageModel $pageModel, LayoutModel $layout, PageRegular
if (!$layout->addEncore) {
return;
}
$this->addEncore($pageModel, $layout, $pageRegular);
if (!isset($this->bundleConfig['use_contao_template_variables']) || true !== $this->bundleConfig['use_contao_template_variables']) {
$this->createEncoreScriptTags($pageRegular);
}
}

/**
Expand All @@ -80,6 +82,9 @@ public function onGeneratePage(PageModel $pageModel, LayoutModel $layout, PageRe
* @throws \Twig\Error\RuntimeError
* @throws \Twig\Error\SyntaxError
* @throws \Exception
*
* @deprecated This method is not used anymore and will be removed in next major release
* @codeCoverageIgnore
*/
public function addEncore(PageModel $page, LayoutModel $layout, PageRegular $pageRegular, ?string $encoreField = 'encoreEntries', bool $includeInline = false): void
{
Expand Down Expand Up @@ -112,4 +117,11 @@ public function cleanGlobalArrays(LayoutModel $layout)

EntryHelper::cleanGlobalArrays($this->bundleConfig);
}

protected function createEncoreScriptTags(PageRegular $pageRegular)
{
$pageRegular->Template->encoreStylesheets = '[[HUH_ENCORE_CSS]]';
$pageRegular->Template->encoreScripts = '[[HUH_ENCORE_JS]]';
$pageRegular->Template->encoreHeadScripts = '[[HUH_ENCORE_HEAD_JS]]';
}
}
Loading

0 comments on commit b2ca1b0

Please sign in to comment.