Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for On Demand BTR #388

Merged
merged 4 commits into from
Apr 17, 2020
Merged
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
176 changes: 88 additions & 88 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@
"sinon": "~4.5.0"
},
"dependencies": {
"@dojo/webpack-contrib": "7.0.0-alpha.15",
"@dojo/webpack-contrib": "7.0.0-beta.2",
"brotli-webpack-plugin": "1.0.0",
"caniuse-lite": "1.0.30000973",
"chalk": "2.4.1",
Expand Down
7 changes: 6 additions & 1 deletion src/base.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,12 @@ export default function webpackConfigFactory(args: any): webpack.Configuration {
const extensions = isLegacy ? ['.ts', '.tsx', '.js'] : ['.ts', '.tsx', '.mjs', '.js'];
const compilerOptions = isLegacy ? {} : { target: 'es2017', module: 'esnext', downlevelIteration: false };
let features = isLegacy ? args.features : { ...(args.features || {}), ...getFeatures('modern') };
features = { ...features, 'dojo-debug': false, 'cldr-elide': true };
features = {
...features,
'dojo-debug': false,
'cldr-elide': true,
'build-time-rendered': !!args['build-time-render']
};
const staticOnly = [];
const assetsDir = path.join(process.cwd(), 'assets');
const assetsDirPattern = new RegExp(assetsDir);
Expand Down
3 changes: 2 additions & 1 deletion src/dev.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,8 @@ window['${libraryName}'].base = '${base}'</script>`,
entries: Object.keys(config.entry!),
basePath,
baseUrl: base,
scope: libraryName
scope: libraryName,
onDemand: Boolean(args.serve && args.watch)
})
);
}
Expand Down
3 changes: 2 additions & 1 deletion src/dist.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,8 @@ function webpackConfig(args: any): webpack.Configuration {
sync: args.singleBundle,
basePath,
baseUrl: base,
scope: libraryName
scope: libraryName,
onDemand: Boolean(args.serve && args.watch)
})
);
}
Expand Down
117 changes: 67 additions & 50 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import * as https from 'https';
import * as expressCompression from 'compression';
import * as proxy from 'http-proxy-middleware';
import * as history from 'connect-history-api-fallback';
import OnDemandBtr from '@dojo/webpack-contrib/build-time-render/BuildTimeRenderMiddleware';

const pkgDir = require('pkg-dir');
const expressStaticGzip = require('express-static-gzip');
Expand All @@ -22,6 +23,20 @@ import logger from './logger';
import { moveBuildOptions } from './util/eject';
import { readFileSync } from 'fs';

export const mainEntry = 'main';
const packageJsonPath = path.join(process.cwd(), 'package.json');
const packageJson = fs.existsSync(packageJsonPath) ? require(packageJsonPath) : {};
export const packageName = packageJson.name || '';

function getLibraryName(name: string) {
return name
.replace(/[^a-z0-9_]/g, ' ')
.trim()
.replace(/\s+/g, '_');
}

const libraryName = packageName ? getLibraryName(packageName) : 'main';

const fixMultipleWatchTrigger = require('webpack-mild-compile');
const hotMiddleware = require('webpack-hot-middleware');
const connectInject = require('connect-inject');
Expand Down Expand Up @@ -71,7 +86,7 @@ function serveStatic(
function build(config: webpack.Configuration, args: any) {
const compiler = createCompiler(config);
const spinner = ora('building').start();
return new Promise<void>((resolve, reject) => {
return new Promise<webpack.Compiler>((resolve, reject) => {
compiler.run((err, stats) => {
spinner.stop();
if (err) {
Expand All @@ -90,7 +105,7 @@ function build(config: webpack.Configuration, args: any) {
'Using `--mode=test` is deprecated and has only built the unit test bundle. This mode will be removed in the next major release, please use `unit` or `functional` explicitly instead.'
);
}
resolve(args.serve);
resolve(compiler);
});
});
}
Expand All @@ -110,19 +125,10 @@ function buildNpmDependencies(): any {
}
}

function fileWatch(config: webpack.Configuration, args: any, app?: express.Application): Promise<void> {
let compiler: webpack.Compiler;
const base = args.base || '/';
if (args.serve && app) {
const timeout = 20 * 1000;
compiler = createWatchCompiler(config);
app.use(base, hotMiddleware(compiler, { heartbeat: timeout / 2 }));
} else {
compiler = createWatchCompiler(config);
}

return new Promise<void>((resolve, reject) => {
async function fileWatch(config: webpack.Configuration, args: any) {
return new Promise<webpack.Compiler>((resolve, reject) => {
const watchOptions = config.watchOptions as webpack.Compiler.WatchOptions;
const compiler = createWatchCompiler(config);
compiler.watch(watchOptions, (err, stats) => {
if (err) {
reject(err);
Expand All @@ -135,17 +141,18 @@ function fileWatch(config: webpack.Configuration, args: any, app?: express.Appli
: 'watching...';
logger(stats.toJson({ warningsFilter }), config, runningMessage, args);
}
resolve();
resolve(compiler);
});
});
}

function serve(config: webpack.Configuration, args: any): Promise<void> {
async function serve(config: webpack.Configuration, args: any) {
const compiler = args.watch ? await fileWatch(config, args) : await build(config, args);
let isHttps = false;
const base = args.base || '/';

const app = express();
app.use(base, function(req, res, next) {
app.use(base, function(req, _, next) {
const { pathname } = url.parse(req.url);
if (req.accepts('html') && pathname && !pathname.match(/\..*$/)) {
req.url = `${req.url}/`;
Expand All @@ -154,6 +161,21 @@ function serve(config: webpack.Configuration, args: any): Promise<void> {
});

const outputDir = (config.output && config.output.path) || process.cwd();
const brtOptions = args['build-time-render'];
if (brtOptions) {
const jsonpName = (config.output && config.output.jsonpFunction) || 'unknown';
const onDemandBtr = new OnDemandBtr({
buildTimeRenderOptions: brtOptions,
scope: libraryName,
base,
compiler,
entries: config.entry ? Object.keys(config.entry) : [],
outputPath: outputDir,
jsonpName
});
app.use(base, (req, res, next) => onDemandBtr.middleware(req, res, next));
}

if (args.mode !== 'dist' || !Array.isArray(args.compression)) {
app.use(base, expressCompression());
}
Expand Down Expand Up @@ -222,43 +244,38 @@ function serve(config: webpack.Configuration, args: any): Promise<void> {
isHttps = true;
}

return Promise.resolve()
.then(() => {
if (args.watch) {
return fileWatch(config, args, app);
}
if (args.watch) {
const timeout = 20 * 1000;
app.use(base, hotMiddleware(compiler, { heartbeat: timeout / 2 }));
}

return build(config, args);
})
.then(() => {
return new Promise<void>((resolve, reject) => {
if (isHttps) {
https
.createServer(
{
key: fs.readFileSync(defaultKey),
cert: fs.readFileSync(defaultCrt)
},
app
)
.listen(args.port, (error: Error) => {
if (error) {
reject(error);
} else {
resolve();
}
});
return new Promise<void>((resolve, reject) => {
if (isHttps) {
https
.createServer(
{
key: fs.readFileSync(defaultKey),
cert: fs.readFileSync(defaultCrt)
},
app
)
.listen(args.port, (error: Error) => {
if (error) {
reject(error);
} else {
resolve();
}
});
} else {
app.listen(args.port, (error: Error) => {
if (error) {
reject(error);
} else {
app.listen(args.port, (error: Error) => {
if (error) {
reject(error);
} else {
resolve();
}
});
resolve();
}
});
});
}
});
}

function warningsFilter(warning: string) {
Expand Down
3 changes: 2 additions & 1 deletion tests/unit/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ describe('command', () => {
'webpack',
'webpack-dev-middleware',
'webpack-hot-middleware',
'webpack-mild-compile'
'webpack-mild-compile',
'@dojo/webpack-contrib/build-time-render/BuildTimeRenderMiddleware'
]);
invalidHookStub = stub().callsFake((name: string, callback: Function) => callback());
doneHookStub = stub().callsFake((name: string, callback: Function) => callback(stats));
Expand Down