All files / packages/design-system/scripts/compile bundle.js

0% Statements 0/51
0% Branches 0/17
0% Functions 0/19
0% Lines 0/46

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125                                                                                                                                                                                                                                                         
// Copyright (c) 2015-present, salesforce.com, inc. All rights reserved
// Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license
 
const Task = require('data.task');
const fs = require('fs');
const I = require('immutable-ext');
const _ = require('lodash');
const path = require('path');
const webpack = require('webpack');
 
const toTask = require('futurize').futurize(Task);
const writeFile = toTask(fs.writeFile);
 
const paths = require('../helpers/paths');
 
const { FOLDERNAME, chunkedEntry, manifest } = require('./helpers');
const webpackConfig = require('./webpack.config');
 
const externals = {
  react: 'React',
  'react-dom': 'ReactDOM',
  'js-beautify': 'JSBeautify',
};
 
// chunked :: Task Error I.Map
const createChunkedConfig = (prefix) =>
  webpackConfig
    .set('externals', externals)
    .setIn(['output', 'library'], ['SLDS', '[name]'])
    .setIn(['output', 'filename'], '[name]') // [name] will already have ".js" appended
    .setIn(['output', 'globalObject'], 'self')
    .setIn(
      ['output', 'chunkLoadingGlobal'],
      `webpackJsonpSLDS_${prefix.replace(new RegExp(_.escapeRegExp(path.sep), 'g'), '_')}`,
    )
    .setIn(['optimization', 'splitChunks'], {
      chunks: 'all',
      name: `${prefix}/common.js`,
      minChunks: 2,
    });
 
// chunkedConfigs :: Task Error (I.List WebpackCfg)
const chunkedConfigs = chunkedEntry.map((entryMap) =>
  entryMap.map((entry, prefix) => createChunkedConfig(prefix).set('entry', entry)).toList(),
);
 
// umd :: WebpackCfg
const umd = webpackConfig
  .set('entry', './scripts/compile/entry.slds.js')
  .setIn(['output', 'library'], 'SLDS')
  .setIn(['output', 'libraryTarget'], 'umd')
  .setIn(['output', 'filename'], `${FOLDERNAME}/slds.umd.js`);
 
// Task Error (List WebpackCfg)
// const configs = Task.of(I.List.of(umd));
const configs = chunkedConfigs.map((configs) =>
  configs
    .unshift(umd)
    .filter((config) =>
      I.Map.isMap(config.get('entry')) ? config.get('entry').count() : config.has('entry'),
    ),
);
 
// watch :: (I.Map, Path, WatchOptions) -> Task Error Stats
const watch = (options = {}) =>
  new Task((reject, resolve) => {
    const config = umd.set('mode', 'development').toJS();
    webpack(config).watch(options, (err, stats) => {
      if (err) return reject(err);
      if (stats.hasErrors()) {
        const errors = stats
          .toJson()
          .errors.map((e) => {
            return typeof e === 'string' ? e : e.message || String(e);
          })
          .join('\n\n');
        console.log(errors);
      }
      resolve(stats);
    });
  });
 
// compile :: (I.Map, Path) -> Task Error Stats
const compile = (configs) =>
  new Task((reject, resolve) => {
    return webpack(configs.toJS()).run((err, stats) => {
      if (err) return reject(err);
      if (stats.hasErrors()) {
        const errors = stats.toJson().errors.map((e) => {
          const errorMessage = typeof e === 'string' ? e : e.message || String(e);
          if (/'lodash'/.test(errorMessage) && /module not found/i.test(errorMessage)) {
            return `
              The module "lodash" should not be imported directly.
              Instead, install the method you need from: https://www.npmjs.com/browse/keyword/lodash-modularized
                1. npm install lodash.truncate --save-dev
                2. add it to "ui/components/helpers/index.js"
                3. import _ from '../../../shared/helpers';
            `;
          }
          return errorMessage;
        });
        return reject(new Error(errors.join(`\n\n-----------------------------------\n\n`)));
      }
      resolve(stats);
    });
  });
 
const compileLibrary = () => configs.chain(compile);
 
const writeManifest = (stats) =>
  manifest
    .map((m) => JSON.stringify(m, null, 2))
    .chain((contents) => writeFile(path.join(paths.dist, 'manifest.json'), contents))
    .map(() => stats);
 
// createLibrary :: () -> Task Error (List Stats)
const createLibrary = () => compileLibrary().chain(writeManifest);
 
module.exports = {
  configs,
  compile,
  watch,
  createLibrary,
};