# @trinitymirrordigital/webpack-config

Standard Webpack setup for all dragonfly projects.

Includes set up for:

- Javascript (through [Babel](https://babeljs.io/))
- [Typescript](https://www.typescriptlang.org/)
- [Pug templates](https://pugjs.org/api/getting-started.html)
- HTML
- css (inc [postcss](https://postcss.org/) for [future css](https://preset-env.cssdb.org/))
- [scss](https://sass-lang.com/documentation/syntax)
- image processing (SVG, JPEG, PNG and GIF)

## Install

```bash
yarn add -D @trinitymirrordigital/webpack-config @trinitymirrordigital/dragonfly-find-files webpack-merge webpack-config-utils
```

## Usage

First create a config.yml with the following data (adjusting as necessary)

You can add anything you want into the config file and it will be returned to you in config object with the webpack default setup. Just be aware that any snake_case will be converted to camelCase.

Below are the list of expected options:

| Option                   | default       | Example                                                                                                                    |
| :----------------------- | :------------ | :------------------------------------------------------------------------------------------------------------------------- |
| context                  | 'src'         | base directory [see here for details](https://webpack.js.org/configuration/entry-context/#context)                         |
| devServer                | {}            | setup for [webpack dev sever](https://webpack.js.org/configuration/dev-server/)                                            |
| public_output_path       | N/A(required) | output directory [see here](https://webpack.js.org/configuration/output/#outputpath)                                       |
| public_dev_output        | N/A(required) | Required to path assets correctly for dev [see here](https://webpack.js.org/configuration/output/#outputpublicpath)        |
| public_root_output       | N/A(required) | Required to path assets correctly for production [see here](https://webpack.js.org/configuration/output/#outputpublicpath) |
| extensions               | N/A           | List of file types to process [see here ](https://webpack.js.org/configuration/resolve/#resolveextensions)                 |
| static_assets_extensions | N/A           | List of static file types to process like images or fonts                                                                  |
| caching_hash             | false         | whether assets are outputed with caching hash e.g '[name].[hash:8].js' or '[name].js'                                      |
| additional_alias         | N/A           | list of aliased modules [see here](https://webpack.js.org/configuration/resolve/#resolvealias)                             |
| exclude_HTML_assets      | N/A           | excludes assets in a html file from processing as regexps [see here](https://webpack.js.org/loaders/html-loader/#sources)  |

## Dragonfly set-up example

For config.yml:

```yaml
default: &default
  public_output_path: 'target/build' # output path
  additional_alias: # Alias for other modules in chameleon-fe otherwise webpack will throw error
    '@trinitymirrordigital/marwood': false
    '@trinitymirrordigital/chameleon-core': false
    '/@trinitymirrordigital/chameleon-core': false
    '@trinitymirrordigital/chameleon-utilities': false
    '/@trinitymirrordigital/chameleon-utilities': false
    '/@trinitymirrordigital/article-service': false
  context: src # root folder for files
  # For finding entry points
  search_pug: 'src/**/*.pug'
  search_scss: 'src/**/!(_)*.scss'
  search_js: 'src/**/*!(.spec).js'
  # Required for production
  asset_properties: 'target/build/assets.properties'
  # Name of dev output (pugs)
  dev_folder: 'dev'
  # Sets default path for dev server
  path_alias: /@DRAGONFLY_STATIC@
  repo_name: 'dragonfly'
  # For output of pug templates for production
  template_folder: 'template'

  static_assets_extensions:
    - .jpg
    - .jpeg
    - .png
    - .gif
    - .tiff
    - .ico
    - .svg
    - .eot
    - .otf
    - .ttf
    - .woff
    - .woff2

  extensions:
    - .mjs
    - .js
    - .js.map
    - .sass
    - .scss
    - .css
    - .css.map
    - .module.sass
    - .module.scss
    - .module.css
    - .pug

development:
  <<: *default
  # Add development specific config here

production:
  <<: *default
  # Add production specific config here
```

Create in your project a webpack.config.js file then add the following:

```javascript
const webpackConfig = require('@trinitymirrordigital/webpack-config');
const fileList = require('@trinitymirrordigital/dragonfly-find-files');
const { merge } = require('webpack-merge');
const { getIfUtils } = require('webpack-config-utils');

module.exports = async (env, args) => {
  // Gets standard set up - see https://bitbucket.org/trinitymirror-ondemand/dragonfly-build-tools/src/master/packages/webpack-config/
  const { webpackConfig, config } = await getWebpackConfig(env, args);
  const { assetProperties, context, devFolder, repoName } = config;

  // for production
  const { VERSION } = process.env;
  const version = VERSION || devFolder;
  // Gets entry points see https://bitbucket.org/trinitymirror-ondemand/dragonfly-build-tools/src/master/packages/dragonfly-find-files/
  const { entry } = await fileList(config, version, context, args.mode);
  // For production build
  const { ifProduction } = getIfUtils(env);
  const wc = ifProduction(
    {
      context: resolve(context),
      entry,
      plugins: [
        // add some production specific plugins here ...
      ],
    },
    // Development specific config here
    {
      context: resolve(context),
      entry: { ...entry, 'webpack-hot-middleware/client': 'webpack-hot-middleware/client?reload=true' },
    },
  );
  // merges with default setup
  return merge(webpackConfig, wc);
};
```

then in package.json add the following:

```json
"scripts": {
  "build": "yarn webpack",
  "webpack": "YAML_CONFIG=webpack/config.yml webpack --config webpack"
},
```

## Cue-web example set-up:

For config.yml

```yaml
default: &default
  additional_alias: # Alias for other modules
    './Configuration/cue.config.js': false
  exclude_HTML_assets: # Removes assets from cue index.html from webpack processing
    - 'Images/.*'
    - 'Configuration'
    - 'scripts.(.*).js'
    - 'polyfills.(.*).js'
    - 'runtime.(.*).js'
    - 'styles.(.*).css'
    - 'vendor.(.*).js'
    - 'main.(.*).js'
  public_dev_output: https://localhost/webpack/ #path set through proxy
  public_output_path: ./dist # output path
  public_root_path: /cue-web/dist/ # production publicPath
  # Sets up static assets
  static_assets_extensions:
    - .jpg
    - .jpeg
    - .png
    - .gif
    - .tiff
    - .ico
    - .svg
    - .eot
    - .otf
    - .ttf
    - .woff
    - .woff2
  # for resolve assets
  extensions:
    - .mjs
    - .js
    - .jsx
    - .ts
    - .tsx
    - .sass
    - .scss
    - .css
    - .module.sass
    - .module.scss
    - .module.css
    - .png
    - .svg
    - .gif
    - .ico
    - .jpeg
    - .jpg

  source_path: assets # where to find entry points

  ###### for html-webpack-plugin #######
  html_output: '../index.html' # Where cue html is outputted
  html_template: './assets/index.html' # Where to get default cue-html

  ####### For @trinitymirrordigital/ cue-webpack-google-tag-manager-plugin #######
  google_tag_id: GTM-PXC7ST9

  ###### for @trinitymirrordigital/cue-templates-plugin ####
  templates_path: template # Where template code are
  cue_url: https://localhost # dev path for assets
  yaml_output: /etc/escenic/cue-web # where the yaml files are outputted in docker image
  start_up_script: /usr/bin/startup.sh # startup script fired when dev-server starts for @trinitymirrordigital/cue-templates-plugin

development:
  <<: *default
  # Extract and emit a css file
  caching_hash: false # disables cache-busting Hash
  # Reference: https://webpack.js.org/configuration/dev-server/
  dev_server:
    https: false
    http2: false
    host: 0.0.0.0
    hot: true
    port: 3131
    headers:
      Access-Control-Allow-Origin: '*'
      Access-Control-Allow-Methods: 'GET, POST, PUT, DELETE, PATCH, OPTIONS'
      Access-Control-Allow-Headers: 'X-Requested-With, content-type, Authorization'
    static:
      watch:
        aggregate_timeout: 300
        ignored: '**/node_modules/**'
        poll: 1000

production:
  <<: *default
  caching_hash: true # enables cache-busting Hash
```

For the webpack config:

```javascript
/* eslint-env node */
const { TemplatePlugin, getFiles } = require('@trinitymirrordigital/cue-templates-plugin');
const webpackSetup = require('@trinitymirrordigital/webpack-config');
const GoogleTagManagerPlugin = require('@trinitymirrordigital/cue-webpack-google-tag-manager-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin');
const { merge } = require('webpack-merge');
const { resolve } = require('path');
const webpack = require('webpack');

module.exports = async (env, argv) => {
  const { webpackConfig, config } = await webpackSetup(env, argv);

  const { cueUrl, googleTagId, htmlOutput, htmlTemplate, publicDevOutput, publicOutputPath, publicRootPath, startUpScript, yamlOutput } = config;

  const files = getFiles(config);
  const publicPath = env.development ? publicDevOutput : publicOutputPath;
  return merge(webpackConfig, {
    // stats: 'normal',
    entry: {
      index: resolve('assets/index.js'),
      ...files,
    },
    output: {
      path: resolve(__dirname, '../', 'dist'),
    },
    plugins: [
      new webpack.DefinePlugin({
        VERSION: JSON.stringify(new Date().getTime()),
        ENVIRONMENT: JSON.stringify(argv.mode),
      }),
      new TemplatePlugin({
        cueUrl,
        mode: argv.mode,
        js: publicRootPath,
        publicPath,
        output: yamlOutput,
        shellScript: startUpScript,
      }),
      new HtmlWebpackPlugin({
        filename: htmlOutput,
        alwaysWriteToDisk: true,
        template: resolve(htmlTemplate),
        excludeChunks: Object.keys(files),
        inject: 'body',
        options: {
          minimize: false, //! env.development,
        },
      }),
      // Adds google tag manger to index.html
      new GoogleTagManagerPlugin({
        id: googleTagId,
      }),
      new HtmlWebpackHarddiskPlugin(),
    ],
  });
};
```

## [Webpack loaders](https://webpack.js.org/configuration/module/#ruleuse)

A list of loaders included in standard config:

- [babel-loader](https://webpack.js.org/loaders/babel-loader/) for Javascript
- [ts-loader](https://github.com/TypeStrong/ts-loader) for Typescript
- [simple-pug-loader](https://github.com/Spence-S/simple-pug-loader) - For Pug templates
- [mini-css-extract-plugin](https://webpack.js.org/plugins/mini-css-extract-plugin/) - To extract styles to spreadsheet
- [postcss-loader](hhttps://webpack.js.org/loaders/postcss-loader/#root) includes [postcss-preset-env](https://github.com/csstools/postcss-preset-env)
- [css-loader](https://webpack.js.org/loaders/css-loader/)
- [sass-loader](https://webpack.js.org/loaders/sass-loader/)
- [svgo-loader](https://github.com/svg/svgo-loader) - To process SVG's - production only

## [Webpack plugins](https://webpack.js.org/configuration/plugins/)

A list of plugins included in standard config:

- [clean-webpack-plugin](https://github.com/johnagan/clean-webpack-plugin) - production only
- [webpack-remove-empty-scripts](https://github.com/webdiscus/webpack-remove-empty-scripts)
- [mini-css-extract-plugin](https://webpack.js.org/plugins/mini-css-extract-plugin/)
- [image-minimizer-webpack-plugin](https://webpack.js.org/plugins/image-minimizer-webpack-plugin/) - production only

## [Webpack minimizers](https://webpack.js.org/configuration/optimization/#optimizationminimizer) (In production only)

A list of minimizers included in standard config:

- [terser-webpack-plugin](https://webpack.js.org/plugins/terser-webpack-plugin/)
- [css-minimizer-webpack-plugin](https://webpack.js.org/plugins/css-minimizer-webpack-plugin/)
- [image-minimizer-webpack-plugin](https://webpack.js.org/plugins/image-minimizer-webpack-plugin/) - with [squoosh](https://github.com/GoogleChromeLabs/squoosh/tree/dev/libsquoosh)

Copyright (c) 2022 "Reach Shared Services Ltd"
