Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 29 additions & 64 deletions bin/bake.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ import { resolve } from 'path';
// packages
import debug from 'debug';
import mri from 'mri';
import { rollup } from 'rollup';
import requireFromString from 'require-from-string';

// local
import { Baker } from '../lib/index.js';
Expand All @@ -17,7 +15,6 @@ import { logErrorMessage } from '../lib/utils.js';
const logger = debug('baker:cli');

const OUTPUT_DIR = '_dist';
const SCREENSHOT_DIR = '_screenshot';

const defaultConfigFile = 'baker.config.js';

Expand All @@ -28,6 +25,7 @@ const defaultConfig = {
domain: undefined,
embeds: 'embeds',
entrypoints: 'scripts/app.js',
imageSrcSizes: undefined,
input: process.cwd(),
layouts: '_layouts',
nunjucksVariables: undefined,
Expand All @@ -41,68 +39,39 @@ const defaultConfig = {
crosswalkPath: undefined,
};

function getDefaultFromConfig(module) {
function getDefaultFromModule(module) {
return module.__esModule ? module.default : module;
}

async function compileAndLoadConfig(pathToConfig) {
const bundle = await rollup({
external: () => true,
input: pathToConfig,
treeshake: false,
});

const {
output: [{ code }],
} = await bundle.generate({
exports: 'named',
format: 'cjs',
interop: 'auto',
});
const loadedConfig = requireFromString(code, pathToConfig);

return getDefaultFromConfig(loadedConfig);
}
async function betterPrepareConfig(flags) {
console.log('betterPrepareConfig:flags');
console.log(JSON.stringify(flags, null, 3));

async function prepareConfig(inputOptions) {
// the input directory everything is relative to
const input = inputOptions.input;
const { input, config } = flags;
console.log('betterPrepareConfig:input');
console.log(input);
console.log('betterPrepareConfig:config');
console.log(config);

// a config parameter was passed
if (inputOptions.config) {
// we check to see if it was passed as a boolean and use our default path to the config, otherwise we use what was given
const pathToConfig = resolve(
input,
inputOptions.config === true ? defaultConfigFile : inputOptions.config
);
const projectConfigFilePath = resolve(input, !!config ? config : defaultConfigFile);
const projectConfigFile = await import(projectConfigFilePath);

inputOptions = await compileAndLoadConfig(pathToConfig);
}
console.log('betterPrepareConfig:projectConfigFile');
console.log(projectConfigFile);

const projectConfig = getDefaultFromModule(projectConfigFile);
console.log('betterPrepareConfig:projectConfig');
console.log(projectConfig.default);

// prep a helper function to resolve paths against input
const resolver = (key) => inputOptions[key] || defaultConfig[key];

const options = {};

options.assets = resolver('assets');
options.createPages = resolver('createPages');
options.data = resolver('data');
options.domain = resolver('domain');
options.embeds = resolver('embeds');
options.entrypoints = resolver('entrypoints');
options.input = resolver('input');
options.layouts = resolver('layouts');
options.nunjucksVariables = resolver('nunjucksVariables');
options.nunjucksFilters = resolver('nunjucksFilters');
options.nunjucksTags = resolver('nunjucksTags');
options.minifyOptions = resolver('minifyOptions');
options.output = resolver('output');
options.pathPrefix = resolver('pathPrefix');
options.staticRoot = resolver('staticRoot');
options.svelteCompilerOptions = resolver('svelteCompilerOptions');
options.crosswalkPath = resolver('crosswalkPath');

return options;
const mergedConfig = {
...defaultConfig,
...projectConfig.default,
};

console.log('betterPrepareConfig:mergedConfig');
console.log(JSON.stringify(mergedConfig, null, 3));

return mergedConfig;
}

const mriConfig = {
Expand Down Expand Up @@ -131,7 +100,7 @@ async function run(args) {
const { _, ...flags } = mri(args, mriConfig);

const command = _[0];
const config = await prepareConfig(flags);
const config = await betterPrepareConfig(flags);

logger('command:', command);
logger('resolved input flags:', config);
Expand All @@ -154,12 +123,8 @@ async function run(args) {
}
break;
case 'screenshot':
// Change a few config options for taking screenshots
const screenshotConfig = { ...config, output: SCREENSHOT_DIR };
const screenshotBaker = new Baker(screenshotConfig);

try {
await screenshotBaker.screenshot();
await baker.screenshots();

console.log(green(bold('The screenshot was a success!')));
} catch (err) {
Expand Down
6 changes: 0 additions & 6 deletions lib/engines/base.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,13 @@ import chokidar from 'chokidar';
import glob from 'fast-glob';

// local
import { getBasePath } from '../env.js';
import { noop, outputFile } from '../utils.js';

/**
* The base builder engine for all asset types. For most engines this will
* handle the majority of tasks.
*/
export class BaseEngine {
subManifests = [];

/**
* @param {object} options
Expand Down Expand Up @@ -84,10 +82,6 @@ export class BaseEngine {
return this.dependencies.add(file);
}

getDependencies() {
return Array.from(this.dependencies);
}

invalidate() {
this.manifest = {};
this.dependencies.clear();
Expand Down
37 changes: 20 additions & 17 deletions lib/engines/rollup.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@ import { polyfillsDynamicImport } from '../paths.js';
import * as svelteConfig from '../../svelte.config.js';

import { createRequire } from 'module';
import { yellow } from 'colorette';

const require = createRequire(import.meta.url);

export class RollupEngine extends BaseEngine {
subManifests = ['modern', 'css', 'legacy'];

constructor({ entrypoints, svelteCompilerOptions = {}, ...args }) {
super(args);
Expand Down Expand Up @@ -99,7 +99,7 @@ export class RollupEngine extends BaseEngine {
'mini-sync/client'
)}";\nimport "${polyfillsDynamicImport}";\n`;

const config = {
return {
input,
plugins: [
!nomodule && prependEntry({ content }),
Expand Down Expand Up @@ -179,10 +179,8 @@ export class RollupEngine extends BaseEngine {
].filter(Boolean),
inlineDynamicImports,
preserveEntrySignatures: false,
onwarn,
onwarn: RollupEngine.onWarn,
};

return config;
}

generateOutputOptions({ dir, nomodule = false }) {
Expand Down Expand Up @@ -287,13 +285,18 @@ export class RollupEngine extends BaseEngine {
const entrypoints = await this.findFiles();

// if there are no entrypoints no need to continue
if (!entrypoints.length) return;
if (!entrypoints.length) {
console.log(
yellow(`No files found for specified entrypoints: ${entrypoints}\n`)
);
return;
}

// use our list of entrypoints to create the Rollup input
const modernInput = this.generateModernInput(entrypoints);

// get our current environment for passing into the input bundle
const { stringified: replaceValues } = getEnvironment(this.pathPrefix);
const { replaceValues } = getEnvironment(this.pathPrefix);

// create the modern bundle
const {
Expand Down Expand Up @@ -341,7 +344,7 @@ export class RollupEngine extends BaseEngine {
const input = this.generateModernInput(entrypoints);

// get our current environment for passing into the input bundle
const { stringified: replaceValues } = getEnvironment(this.pathPrefix);
const { replaceValues } = getEnvironment(this.pathPrefix);

// generate the Rollup inputOptions
const inputOptions = this.generateInputOptions(input, replaceValues);
Expand Down Expand Up @@ -395,15 +398,15 @@ export class RollupEngine extends BaseEngine {
}
});
}
}

export function onwarn(warning, onwarn) {
if (
warning.code === 'CIRCULAR_DEPENDENCY' &&
/[/\\]d3-\w+[/\\]/.test(warning.message)
) {
return;
}
static onWarn(warning, onwarn) {
if (
warning.code === 'CIRCULAR_DEPENDENCY' &&
/[/\\]d3-\w+[/\\]/.test(warning.message)
) {
return;
}

onwarn(warning);
onwarn(warning);
}
}
16 changes: 6 additions & 10 deletions lib/env.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,7 @@ export const isProductionEnv = nodeEnv === 'production';

export const inDebugMode = Boolean(DEBUG);

/**
* Regex for grabbing any environmental variables that may start with "BAKER_".
* @type {RegExp}
*/
const BAKER_REGEX = /^BAKER_/i;
const BAKER_PREFIX = 'BAKER_';

/**
* @param {string} pathPrefix
Expand All @@ -26,10 +22,10 @@ export function getEnvironment(pathPrefix) {
const keys = Object.keys(process.env);

// find any of them that match our regex for BAKER_ exclusive ones
const bakerKeys = keys.filter((key) => BAKER_REGEX.test(key));
const bakerKeys = keys.filter((key) => key.startsWith(BAKER_PREFIX));

// build the object of environment variables
const raw = bakerKeys.reduce(
const vars = bakerKeys.reduce(
(env, key) => {
env[key] = process.env[key];
return env;
Expand All @@ -43,12 +39,12 @@ export function getEnvironment(pathPrefix) {
);

// Stringify all values so we can pass it directly to rollup-plugin-replace
const stringified = Object.keys(raw).reduce((env, key) => {
env[`process.env.${key}`] = JSON.stringify(raw[key]);
const replaceValues = Object.keys(vars).reduce((env, key) => {
env[`process.env.${key}`] = JSON.stringify(vars[key]);
return env;
}, {});

return { raw, stringified };
return { vars, replaceValues };
}

export function getBasePath(domain, pathPrefix) {
Expand Down
23 changes: 23 additions & 0 deletions lib/filters/srcSets.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Baker } from '../index.js';

function maxstache(str, ctx) {
return str
.split(/\{|\}/)
.map((t, i) => (!(i % 2) ? t : ctx[t]))
.join('');
}

/**
* @param {number[]} sizes
* @param {Baker} instance
**/
export function createSrcSetFilter(sizes, instance) {
return function createSrcSet(source) {
return sizes
.map((size) => {
const url = instance.getStaticPath(`${maxstache(source, { size })}`);
return `${url} ${size}w`;
})
.join(', ');
};
}
Loading
Loading