Add JS modules support & use for GOVUKFrontend

The JS for GOVUKFrontend components is available
individually so you can only include what you
need:

https://github.com/alphagov/govuk-frontend/blob/v2.13.0/docs/installation/installing-with-npm.md#option-2-import-javascript

This uses the JS Modules syntax:

*[JS module](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules)

Our JS is delivered as one file so we need to use
a bundler to convert the modules to a single file.

This adds a build step to transpile all modules
into a single file, which is then added to the
files combined into the one that get delivered.

Rollup is used as the simplest bundler to use for
this purpose. It also introduces the least
boilerplate JS.

Note: the CommonJS plugin is needed as GOV.UK
Frontend components are published as UMD modules.

In future, this work should let us work on this
story dependencies:

https://www.pivotaltracker.com/story/show/165380360
This commit is contained in:
Tom Byers
2019-10-11 10:26:25 +01:00
parent 3511f0b726
commit efe7e2f35e
4 changed files with 801 additions and 4 deletions

View File

@@ -6,6 +6,9 @@
// 1. LIBRARIES
// - - - - - - - - - - - - - - -
const { src, pipe, dest, series, parallel, watch } = require('gulp');
const rollup = require('rollup');
const rollupPluginCommonjs = require('rollup-plugin-commonjs');
const rollupPluginNodeResolve = require('rollup-plugin-node-resolve');
const stylish = require('jshint-stylish');
const plugins = {};
@@ -50,6 +53,27 @@ const copy = {
};
const bundleJavaScriptModules = async function () {
const bundle = await rollup.rollup({
input: paths.src + 'javascripts/modules/all.mjs',
plugins: [
rollupPluginNodeResolve({
mainFields: ['module', 'main']
}),
rollupPluginCommonjs({
include: 'node_modules/**'
})
]
});
await bundle.write({
file: paths.src + 'javascripts/modules/all.js',
format: 'iife',
name: 'GOVUKFrontend'
});
};
const javascripts = () => {
return src([
paths.toolkit + 'javascripts/govuk/modules.js',
@@ -86,7 +110,7 @@ const javascripts = () => {
paths.npm + 'diff-dom/diffDOM.js',
paths.npm + 'timeago/jquery.timeago.js',
paths.npm + 'textarea-caret/index.js',
paths.govuk_frontend + 'all.js'
paths.src + 'javascripts/modules/all.js'
]))
.pipe(plugins.uglify())
.pipe(plugins.concat('all.js'))
@@ -157,7 +181,10 @@ const lint = {
.pipe(plugins.sassLint.failOnError());
},
'js': (cb) => {
return src(paths.src + 'javascripts/**/*.js')
return src(
paths.src + 'javascripts/**/*.js',
{ ignore: paths.src + 'javascripts/modules/*.js' } // ignore bundler boilerplate JS
)
.pipe(plugins.jshint())
.pipe(plugins.jshint.reporter(stylish))
.pipe(plugins.jshint.reporter('fail'))
@@ -173,7 +200,10 @@ const defaultTask = parallel(
),
series(
copy.error_pages,
javascripts,
series(
bundleJavaScriptModules,
javascripts
),
sass
)
);