Skip to content

Commit

Permalink
refactor: Separate internal concepts of config and env
Browse files Browse the repository at this point in the history
  • Loading branch information
rschristian committed Nov 18, 2022
1 parent 7eaaabb commit bed36ab
Show file tree
Hide file tree
Showing 11 changed files with 122 additions and 99 deletions.
3 changes: 1 addition & 2 deletions packages/cli/src/commands/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,6 @@ async function command(src, argv) {
argv.src = src || argv.src;
// add `default:true`s, `--no-*` disables
argv.prerender = toBool(argv.prerender);
argv.production = toBool(argv.production);

let cwd = resolve(argv.cwd);

Expand All @@ -94,7 +93,7 @@ async function command(src, argv) {
await promisify(rimraf)(dest);
}

let stats = await runWebpack(argv, false);
let stats = await runWebpack(argv, true);

if (argv.json) {
await runWebpack.writeJsonStats(cwd, stats);
Expand Down
3 changes: 1 addition & 2 deletions packages/cli/src/commands/watch.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,6 @@ async function command(src, argv) {
argv.refresh = argv.rhl;
}
argv.src = src || argv.src;
argv.production = false;
if (argv.sw) {
argv.sw = toBool(argv.sw);
}
Expand All @@ -120,7 +119,7 @@ async function command(src, argv) {
}
}

return runWebpack(argv, true);
return runWebpack(argv, false);
}

async function determinePort(port) {
Expand Down
7 changes: 5 additions & 2 deletions packages/cli/src/lib/babel-config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
const { tryResolveConfig } = require('../util');

module.exports = function (env) {
const { babelConfig, cwd, isProd, refresh } = env;
/**
* @param {boolean} isProd
*/
module.exports = function (config, isProd) {
const { babelConfig, cwd, refresh } = config;

const resolvedConfig =
babelConfig &&
Expand Down
7 changes: 6 additions & 1 deletion packages/cli/src/lib/webpack/render-html-plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,12 @@ function read(path) {
return readFileSync(resolve(__dirname, path), 'utf-8');
}

module.exports = async function renderHTMLPlugin(config) {
/**
* @param {import('../../../types').Env} env
*/
module.exports = async function renderHTMLPlugin(config, env) {
const { cwd, dest, src } = config;

const inProjectTemplatePath = resolve(src, 'template.html');
let template = defaultTemplate;
if (existsSync(inProjectTemplatePath)) {
Expand Down Expand Up @@ -89,6 +93,7 @@ module.exports = async function renderHTMLPlugin(config) {
inlineCss: config['inline-css'],
preload: config.preload,
config,
env,
preRenderData: values,
CLI_DATA: { preRenderData: { url, ...routeData } },
ssr: config.prerender ? prerender({ cwd, dest, src }, values) : '',
Expand Down
69 changes: 40 additions & 29 deletions packages/cli/src/lib/webpack/run-webpack.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,29 @@ const serverConfig = require('./webpack-server-config');
const transformConfig = require('./transform-config');
const { error, isDir, warn } = require('../../util');

async function devBuild(env) {
let config = await clientConfig(env);
/**
* @param {import('../../../types').Env} env
*/
async function devBuild(config, env) {
const webpackConfig = await clientConfig(config, env);

await transformConfig(env, config);
await transformConfig(webpackConfig, config, env);

let compiler = webpack(config);
let compiler = webpack(webpackConfig);
return new Promise((res, rej) => {
compiler.hooks.beforeCompile.tap('CliDevPlugin', () => {
if (env['clear']) clear(true);
});

compiler.hooks.done.tap('CliDevPlugin', stats => {
let devServer = config.devServer;
let devServer = webpackConfig.devServer;
let protocol = process.env.HTTPS || devServer.https ? 'https' : 'http';
let host = process.env.HOST || devServer.host || 'localhost';
if (host === '0.0.0.0' && process.platform === 'win32') {
host = 'localhost';
}
let serverAddr = `${protocol}://${host}:${bold(env.port)}`;
let localIpAddr = `${protocol}://${ip.address()}:${bold(env.port)}`;
let serverAddr = `${protocol}://${host}:${bold(config.port)}`;
let localIpAddr = `${protocol}://${ip.address()}:${bold(config.port)}`;

if (stats.hasErrors()) {
process.stdout.write(red('Build failed!\n\n'));
Expand All @@ -45,26 +48,28 @@ async function devBuild(env) {

compiler.hooks.failed.tap('CliDevPlugin', rej);

let server = new DevServer(config.devServer, compiler);
let server = new DevServer(webpackConfig.devServer, compiler);
server.start();
res(server);
});
}

async function prodBuild(env) {
env = { ...env, isServer: false, dev: !env.production, ssr: false };
let config = await clientConfig(env);
await transformConfig(env, config);
/**
* @param {import('../../../types').Env} env
*/
async function prodBuild(config, env) {
if (config.prerender) {
const serverEnv = { ...env, isServer: true };

if (env.prerender) {
const serverEnv = Object.assign({}, env, { isServer: true, ssr: true });
let ssrConfig = serverConfig(serverEnv);
await transformConfig(serverEnv, ssrConfig);
let serverCompiler = webpack(ssrConfig);
const serverWebpackConfig = serverConfig(config, serverEnv);
await transformConfig(serverWebpackConfig, config, serverEnv);
const serverCompiler = webpack(serverWebpackConfig);
await runCompiler(serverCompiler);
}

let clientCompiler = webpack(config);
const clientWebpackConfig = await clientConfig(config, env);
await transformConfig(clientWebpackConfig, config, env);
const clientCompiler = webpack(clientWebpackConfig);

try {
let stats = await runCompiler(clientCompiler);
Expand Down Expand Up @@ -220,20 +225,26 @@ function stripLoaderFromModuleNames(m) {
return m;
}

module.exports = function (env, watch = false) {
env.isProd = env.production; // shorthand
env.isWatch = !!watch; // use HMR?
env.cwd = resolve(env.cwd || process.cwd());

// env.src='src' via `build` default
let src = resolve(env.cwd, env.src);
env.src = isDir(src) ? src : env.cwd;
/**
* @param {boolean} isProd
*/
module.exports = function (argv, isProd) {
const env = {
isProd,
isDev: !isProd,
isServer: false,
};
const config = argv;
config.cwd = resolve(argv.cwd || process.cwd());

// config.src='src' via `build` default
const src = resolve(config.cwd, argv.src);
config.src = isDir(src) ? src : config.cwd;

// attach sourcing helper
env.source = dir => resolve(env.src, dir);
config.source = dir => resolve(config.src, dir);

// determine build-type to run
return (watch ? devBuild : prodBuild)(env);
return (isProd ? prodBuild : devBuild)(config, env);
};

module.exports.writeJsonStats = writeJsonStats;
27 changes: 15 additions & 12 deletions packages/cli/src/lib/webpack/transform-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ const { error, esmImport, tryResolveConfig, warn } = require('../../util');
const FILE = 'preact.config';
const EXTENSIONS = ['js', 'json'];

async function findConfig(env) {
async function findConfig(cwd) {
let idx = 0;
for (idx; idx < EXTENSIONS.length; idx++) {
let config = `${FILE}.${EXTENSIONS[idx]}`;
let path = resolve(env.cwd, config);
let configFile = `${FILE}.${EXTENSIONS[idx]}`;
let path = resolve(cwd, configFile);
try {
await stat(path);
return { configFile: config, isDefault: true };
return { configFile, isDefault: true };
} catch (e) {}
}

Expand Down Expand Up @@ -90,17 +90,20 @@ function parseConfig(config) {
return transformers;
}

module.exports = async function (env, webpackConfig) {
/**
* @param {import('../../../types').Env} env
*/
module.exports = async function (webpackConfig, config, env) {
const { configFile, isDefault } =
env.config !== 'preact.config.js'
? { configFile: env.config, isDefault: false }
: await findConfig(env);
config.config !== 'preact.config.js'
? { configFile: config.config, isDefault: false }
: await findConfig(config.cwd);

const cliConfig = tryResolveConfig(
env.cwd,
config.cwd,
configFile,
isDefault,
env.verbose
config.verbose
);

if (!cliConfig) return;
Expand All @@ -111,15 +114,15 @@ module.exports = async function (env, webpackConfig) {
} catch (error) {
warn(
`Failed to load preact-cli config file, using default!\n${
env.verbose ? error.stack : error.message
config.verbose ? error.stack : error.message
}`
);
return;
}

const transformers = parseConfig((m && m.default) || m);

const helpers = new WebpackConfigHelpers(env.cwd);
const helpers = new WebpackConfigHelpers(config.cwd);
for (let [transformer, options] of transformers) {
try {
await transformer(webpackConfig, env, helpers, options);
Expand Down
17 changes: 10 additions & 7 deletions packages/cli/src/lib/webpack/webpack-base-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,17 @@ function getSassConfiguration(...includePaths) {
}

/**
* @param {import('../../../types').Env} env
* @returns {import('webpack').Configuration}
*/
module.exports = function createBaseConfig(env) {
const { cwd, isProd, src, source } = env;
module.exports = function createBaseConfig(config, env) {
const { cwd, src, source } = config;
const { isProd, isServer } = env;

// Apply base-level `env` values
env.dest = resolve(cwd, env.dest || 'build');
env.manifest = readJson(source('manifest.json')) || {};
env.pkg = readJson(resolve(cwd, 'package.json')) || {};
config.dest = resolve(cwd, config.dest || 'build');
config.manifest = readJson(source('manifest.json')) || {};
config.pkg = readJson(resolve(cwd, 'package.json')) || {};

// use browserslist config environment, config default, or default browsers
// default browsers are '> 0.5%, last 2 versions, Firefox ESR, not dead'
Expand Down Expand Up @@ -148,7 +151,7 @@ module.exports = function createBaseConfig(env) {
resolve: { mainFields: ['module', 'jsnext:main', 'browser', 'main'] },
type: 'javascript/auto',
loader: require.resolve('babel-loader'),
options: createBabelConfig(env),
options: createBabelConfig(config, isProd),
},
{
// LESS
Expand Down Expand Up @@ -291,7 +294,7 @@ module.exports = function createBaseConfig(env) {
new RemoveEmptyScriptsPlugin(),
new MiniCssExtractPlugin({
filename:
isProd && !env.isServer ? '[name].[contenthash:5].css' : '[name].css',
isProd && !isServer ? '[name].[contenthash:5].css' : '[name].css',
chunkFilename: isProd
? '[name].chunk.[contenthash:5].css'
: '[name].chunk.css',
Expand Down
Loading

0 comments on commit bed36ab

Please sign in to comment.