Fri Feb 05 2021
Copied to clipboard! Copy reply
  • 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
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331
  • 332
  • 333
  • 334
  • 335
  • 336
  • 337
  • 338
  • 339
  • 340
  • 341
  • 342
  • 343
  • 344
  • 345
  • 346
  • 347
  • 348
  • 349
  • 350
  • 351
  • 352
  • 353
  • 354
  • 355
  • 356
  • 357
  • 358
  • 359
  • 360
  • 361
  • 362
  • 363
  • 364
  • 365
  • 366
  • 367
  • 368
  • 369
  • 370
  • 371
  • 372
  • 373
  • 374
  • 375
  • 376
  • 377
  • 378
  • 379
  • 380
  • 381
  • 382
  • 383
  • 384
  • 385
  • 386
  • 387
  • 388
  • 389
  • 390
  • 391
  • 392
  • 393
  • 394
  • 395
  • 396
  • 397
  • 398
  • 399
  • 400
  • 401
  • 402
  • 403
  • 404
  • 405
  • 406
  • 407
  • 408
  • 409
  • 410
  • 411
  • 412
  • 413
  • 414
  • 415
  • 416
  • 417
  • 418
  • 419
  • 420
  • 421
  • 422
  • 423
  • 424
  • 425
  • 426
  • 427
  • 428
  • 429
  • 430
  • 431
  • 432
  • 433
  • 434
  • 435
  • 436
  • 437
  • 438
const fse = require("fs-extra");
const exec = require("child_process").execSync;
const yaml = require("js-yaml");

/**
 * The environment. This will be used to load the right
 * .env.* file when compiling. It should be either
 * 'staging' or 'production'. Use production as default to ensure
 * urls with .stg in them never make it to production.
 */
const ENV = process.env.env || "production";

/*
 * The locale we are generating pages for.
 * LOCALE can be either en, es, de, etc.
 */
const LOCALE = process.env.locale || "en";

/**
 * Config values to store in env vars so we can use in components.
 * It's like .env files, but lets us use yaml. Seemed like the better approach
 * as opposed to having .env.es.stg, .env.en.stg, .env.es.prod, .env.en.prod, etc
 */
const CONFIG = require("dotenv-yaml").config({ path: `.env.${ENV}.yaml` }).parsed;

/*
 * A Group is basically a template. For instance,
 * if GROUP is 'catalog-pages', we will store our app in
 * `_nuxt-catalog-pages/`. Pages that don't belong in a group,
 * will use default `_nuxt-single-pages/` dir. So this means that when
 * deploying a page that does not belong to a group (ie, homepage),
 * all other non-group pages will be deployed too.
 */

const GROUP = process.env.group || null;

/**
 * This is the deploy folder. Normally it should just be 'dist/'.
 * Because landing page generation has to create two dist folders (one for
 * `en' and one for 'es' locale), we have to change the name, so that the
 * contents of 'dist/` don't get overwritten when generating the next locale
 */

const distDir = GROUP === "landing-pages" ? `dist-${GROUP}-${LOCALE}` : "dist";

/**
 * Routes for our dynamic pages  - normally a dir inside group/.
 * If the group is single-pages, we don't need a route because
 * those are the pages on the root ftp server (ie, /homepage, /freetrial, /demo, etc), and
 * are not dynamic. Read more about dynamic routing here
 * https://nuxtjs.org/api/configuration-generate/#routes
 */
const routesMap = {
  "landing-pages": getLandingPages,
  "catalog-pages": getCatalogPages,
};
const route = GROUP === "single-pages" ? null : routesMap[GROUP];

/**
 * The publicPath, which is determined by LOCALE and GROUP.
 * This is the _nuxt* dir, where js files for the app are stored.
 * We create different ones so we can deploy parts of the site independently,.
 * Each group gets its own app folder (_nuxt-<group>-<locale>) so we can deploy
 * a group by itself without breaking the site. For example, deploying `single-pages`
 * will deploy the html files, and js app directory _nuxt-single-pages, leaving the html files
 * and app directory of landing-pages untouched (_nuxt-landing-pages)
 */

const publicPath = `/_nuxt-${GROUP}-${LOCALE}`;

export default {
  target: "static",

  env: {
    LOCALE,
    ...CONFIG[LOCALE],
  },

  /*
   ** Customize the progress-bar color
   */
  loading: false,

  /*
   ** Global CSS
   */
  css: ["~/assets/css/normalize.css"],

  /*
   ** Global <head> element
   ** Only GTM here at the moment. May later add as a plugin to keep nuxt config cleaner
   ** Not using the community GTM module anymore since it does not allow for customization of GTM environments
   */
  head: {
    script: [
      {
        hid: "gtm",
        innerHTML: `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl${
          ENV === "staging" ? "+ '&gtm_auth=p61245cv7fFWvNjVaBm10g&gtm_preview=env-249&gtm_cookies_win=x'" : ""
        };f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','GTM-TLH67WS');`,
      },
    ],
    __dangerouslyDisableSanitizersByTagID: {
      gtm: ["innerHTML"],
      gtmnoscript: ["innerHTML"],
    },
    noscript: [
      {
        hid: "gtmnoscript",
        innerHTML: `<iframe src="https://www.googletagmanager.com/ns.html?id=GTM-TLH67WS${
          ENV === "staging" ? "&gtm_auth=A4nRhWPBAjR6j8iRa343MQ&gtm_preview=env-249&gtm_cookies_win=x" : ""
        }" height="0" width="0" style="display:none visibility:hidden"></iframe>`,
      },
    ],
  },

  /*
   ** Plugins to load before mounting the App
   */
  plugins: ["~/plugins/event-bus", { src: "~/plugins/swiper.js", mode: "client" }],

  generate: {
    dir: distDir,
    crawler: false,
    routes: route ? route() : null,
  },

  hooks: {
    "generate:route": ({ route, setPayload }) => {
      /*
       * FastSpring Localization Routing
       */
      if (["/ww-en", "/ww-pt", "/ww-es"].indexOf(route) > -1) {
        const fastspringYamlMap = {
          "/ww-en": "en",
          "/ww-pt": "pt",
          "/ww-es": "es",
        };
        const locale = fastspringYamlMap[route];
        setPayload({ locale: locale });
      }

      if (/gift/.test(route)) {
        let locale = LOCALE;
        if (locale === "pt") {
          locale = "en";
        }
        const model = JSON.parse(fse.readFileSync(`../data-models/${locale}/json/products/gift.json`, "utf8"));
        setPayload({ model });
      }

      if (/crm-coaching/.test(route)) {
        let locale = LOCALE;
        if (locale === "pt") {
          locale = "en";
        }
        const model = JSON.parse(fse.readFileSync(`../data-models/${locale}/json/products/crm-coaching.json`, "utf8"));
        setPayload({ model });
      }

      if (/^\/coaching$/.test(route)) {
        let locale = LOCALE;
        if (locale === "pt") {
          locale = "en";
        }
        const model = JSON.parse(fse.readFileSync(`../data-models/${locale}/json/products/crm-coaching.json`, "utf8"));
        setPayload({ model });
      }
    },

    // If we have a group, delete any other file that isn't the html files we need,
    // so that Jenkins can push everything inside dist/ with no worries.
    // Similarly, if we're deploying single-pages (pages that don't belong to a group),
    // we remove the groups/ directory.
    "generate:done": () => {
      /*
       * Landing pages is a bit of a special case because we deploy both en and es
       * locale with 1 deploy. So after nuxt is done generating each locale, we bring the
       * interested folders into the dist/ folder so Jenkins can push it in one go.
       */
      if (GROUP === "landing-pages") {
        fse.ensureDirSync("dist/groups");
        // Takes dist-landing-pages-{LOCALE} and put in to dist/landing-pages-{LOCALE}
        exec(`cp -R ${distDir}/groups/ dist/`);

        // Copy the _nuxt folder from dist-landing-pages-{LOCALE} into dist/
        exec(`cp -R ${distDir}/${publicPath}/ dist/`);

        // Copy assets too
        exec(`cp -R ${distDir}/nuxt-assets/ dist/`);
      }

      // Try to put data-models inside /nuxt-assets in case we're compiling
      // product pages. This will let, ie, catalog pages include from
      // `<script src="/data-models/,,,>
      try {
        exec("cp -R ../data-models dist/");
        exec("cp -R ../data-models/ dist/nuxt-assets/");
      } catch (e) {
        // Catch error
      }

      // If we're not uploading single pages, delete everything
      // that is not the 'groups' directory so when rsync pushes everything
      // inside dist/, singles pages (home page & siblings) don't go with it.
      //
      if (GROUP !== "single-pages") {
        exec("ls -d dist/* | egrep -v 'groups|static|nuxt-assets|_nuxt*|data-models' | xargs rm -rf"); // TODO: Maybe check quotes around 'groups|static...' section
      }

      if (LOCALE === "pt") {
        exec("ls -d dist/* | egrep -v 'index.html|_nuxt*|nuxt-assets|data-models'| xargs rm -rf"); // TODO: Maybe check quotes around 'groups|static...' section
      }
    },

    "generate:routeFailed": (errors) => {
      console.log("-------- ERROR GENERATING ROUTES --------");
      console.log(errors.route);
      console.log(errors.errors[0].error);
      process.exit(1);
    },
  },

  router: {
    extendRoutes(routes, resolve) {
      // Use these routes for /lp pages. Not needed for root paths.
      routes.push(
        
        {
          path: "/lp/(sbsr|sbsr-es)/*",
          component: resolve(__dirname, "pages/groups/landing-pages/sbsr/_sbsr/_.vue"),
        },
        {
          path: "/lp/(ulu|ulu-es)/*",
          component: resolve(__dirname, "pages/groups/landing-pages/ulu/_ulu/_.vue"),
        },
       
        {
          path: "/lp/(ppc|ppc-es)/*",
          component: resolve(__dirname, "pages/groups/landing-pages/sbsr/_sbsr/_.vue"),
        },
        {
          path: "/lp/(nsp|nsp-es)/*",
          component: resolve(__dirname, "pages/groups/landing-pages/nsp/_nsp/_.vue"),
        },
        {
          path: "/(buy|comprar)-*",
          component: resolve(__dirname, "pages/groups/catalog-pages/_.vue"),
        },
        {
          path: "/lp/awards",
          component: resolve(__dirname, "pages/awards.vue"),
        },
        {
          path: "/lp/form-mobile-success",
          component: resolve(__dirname, "pages/form-mobile-success.vue"),
        },
        {
          path: "/lp/nyced",
          component: resolve(__dirname, "pages/nyced.vue"),
        },
        {
          path: "/lp/system-requirements",
          component: resolve(__dirname, "pages/system-requirements.vue"),
        },
        {
          path: "/lp/gratis-para-estudiantes",
          component: resolve(__dirname, "pages/gratis-para-estudiantes.vue"),
        },
        {
          path: "/lp/ccpa",
          component: resolve(__dirname, "pages/ccpa.vue"),
        },
        {
          path: "/lp/live-lessons",
          component: resolve(__dirname, "pages/live-lessons.vue"),
        },
        {
          path: "/lp/partners",
          component: resolve(__dirname, "pages/partners.vue"),
        },
        {
          path: "/lp/unlimited-languages-upgrade",
          component: resolve(__dirname, "pages/unlimited-languages-upgrade.vue"),
        },
        {
          path: "/lp/page-not-found",
          component: resolve(__dirname, "pages/page-not-found.vue"),
        },
        {
          path: "/lp/crm-coaching",
          component: resolve(__dirname, "pages/crm-coaching.vue"),
        },
        {
          path: "/lp/about",
          component: resolve(__dirname, "pages/about.vue"),
        },
        {
          path: "/lp/tryitnow",
          component: resolve(__dirname, "pages/tryitnow.vue"),
        },
        {
          path: "/homeschool/reviews",
          component: resolve(__dirname, "pages/homeschool-reviews.vue"),
        }
      );
    },
  },

  /*
   ** Nuxt.js dev-modules
   */
  buildModules: [
    // Doc: https://github.com/nuxt-community/stylelint-module
    //'@nuxtjs/stylelint-module',
    ["@nuxtjs/router-extras", { routerNativeAlias: false }],
  ],

  /*
   ** Nuxt.js modules and config/options
   */
  modules: ["@nuxtjs/axios", "@nuxtjs/apollo", "@nuxtjs/style-resources"],

  styleResources: {
    stylus: ["~/assets/css/variables.styl"],
  },

  apollo: {
    clientConfigs: {
      default: "~/plugins/apollo.js",
    },
  },

  /*
   * Build configuration
   */
  build: {
    // The _nuxt directory inside dist/
    publicPath,

    // Watch this directory for changes, too.
    watch: ["~/data"],

    html: {
      minify: {
        collapseBooleanAttributes: true,
        decodeEntities: true,
        minifyCSS: true,
        minifyJS: true,
        processConditionalComments: true,
        removeEmptyAttributes: true,
        removeRedundantAttributes: false,
        trimCustomFragments: true,
        useShortDoctype: true,
      },
    },

    // Until this bug is fixed https://github.com/nuxt/nuxt.js/issues/3877, use this.
    splitChunks: {
      layouts: true,
      //pages: true,
      //commons: true,
    },

    /*
     ** You can extend webpack config here
     */
    extend(config, ctx) {
      // This is so we can use import yaml files. Handy during dev
      config.module.rules.push({
        test: /\.yaml$/,
        loader: "js-yaml-loader",
      });

      // Enable debugging in editor such as VSCode
      if (ctx.isDev) {
        config.devtool = ctx.isClient ? "source-map" : "inline-source-map";
      }

      // Run ESLint on build and enforce
      if (ctx.isDev && ctx.isClient) {
        config.module.rules.push({
          enforce: "pre",
          test: /\.(js|vue)$/,
          loader: "eslint-loader",
          exclude: /(node_modules)/,
        });
      }
    },
  },
};

/**
 * Generates routes for landing pages.
 *
 * @return {Array} array of objects.
 */
function getLandingPages() {
  // We use JSON because the js model has "window.data = {...}" prefixed.
  const models = fse.readdirSync("../data-models/en/json/products");
  const routes = [];
  // Landing page templates - scan pages/groups/landing-pages for dirs
  const directories = fse.readdirSync("./pages/groups/landing-pages");
  for (const dir of directories) {
    // If we have a locale other than 'en', append it to directory. ie, sbsr-es.
    const dynamicDirectory = LOCALE === "en" ? dir : `${dir}-${LOCALE}`;
    for (const model of models) {
      // Remove '.json' from filename
      const name = model.slice(0, -5);
      const modelJSON = JSON.parse(fse.readFileSync(`../data-models/${LOCALE}/json/products/${model}`, "utf8"));
      routes.push({
        route: `/groups/landing-pages/${dir}/${dynamicDirectory}/${name}`,
        payload: { model: modelJSON },
      });
    }
  }
  return routes;
}

/**
 * Generates routes for catalog pages.
 *
 * @return {Array} array of objects.
 */
function getCatalogPages() {
  const languages = require(`./locales/config/languages/${LOCALE}.js`).default;
  const yamlFile = yaml.safeLoad(fse.readFileSync(`./data/catalog-pages/${LOCALE}.yaml`, "utf8"));
  return languages.map((language) => {
    return {
      route: `/groups/catalog-pages/${language.catalog}`,
      payload: {
        language,
        content: yamlFile,
      },
    };
  });
}