Skip to content

Commit

Permalink
chore(webpack): minify injected sources (#4946)
Browse files Browse the repository at this point in the history
  • Loading branch information
JoelEinbinder committed Jan 9, 2021
1 parent 135e034 commit 31d980f
Show file tree
Hide file tree
Showing 11 changed files with 53 additions and 22 deletions.
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -62,6 +62,7 @@
"@types/react-dom": "^17.0.0",
"@types/resize-observer-browser": "^0.1.4",
"@types/rimraf": "^3.0.0",
"@types/webpack": "^4.41.25",
"@types/ws": "7.2.6",
"@typescript-eslint/eslint-plugin": "^3.10.1",
"@typescript-eslint/parser": "^3.10.1",
Expand Down
7 changes: 5 additions & 2 deletions src/cli/injected/recorder.webpack.config.js
Expand Up @@ -17,10 +17,11 @@
const path = require('path');
const InlineSource = require('../../server/injected/webpack-inline-source-plugin');

/** @type {import('webpack').Configuration} */
module.exports = {
entry: path.join(__dirname, 'recorder.ts'),
devtool: 'source-map',
mode: 'development',
mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
devtool: false,
module: {
rules: [
{
Expand All @@ -38,6 +39,8 @@ module.exports = {
},
output: {
libraryTarget: 'var',
libraryExport: 'default',
library: 'pwExport',
filename: 'recorderSource.js',
path: path.resolve(__dirname, '../../../lib/server/injected/packed')
},
Expand Down
7 changes: 5 additions & 2 deletions src/debug/injected/consoleApi.webpack.config.js
Expand Up @@ -17,10 +17,11 @@
const path = require('path');
const InlineSource = require('../../server/injected/webpack-inline-source-plugin');

/** @type {import('webpack').Configuration} */
module.exports = {
entry: path.join(__dirname, 'consoleApi.ts'),
devtool: 'source-map',
mode: 'development',
mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
devtool: false,
module: {
rules: [
{
Expand All @@ -38,6 +39,8 @@ module.exports = {
},
output: {
libraryTarget: 'var',
library: 'pwExport',
libraryExport: 'default',
filename: 'consoleApiSource.js',
path: path.resolve(__dirname, '../../../lib/server/injected/packed')
},
Expand Down
7 changes: 5 additions & 2 deletions src/server/dom.ts
Expand Up @@ -82,9 +82,12 @@ export class FrameExecutionContext extends js.ExecutionContext {
for (const [name, { source }] of this.frame._page.selectors._engines)
custom.push(`{ name: '${name}', engine: (${source}) }`);
const source = `
new (${injectedScriptSource.source})([
(() => {
${injectedScriptSource.source}
return new pwExport([
${custom.join(',\n')}
])
]);
})();
`;
this._injectedScriptPromise = this._delegate.rawEvaluate(source).then(objectId => new js.JSHandle(this, 'object', objectId));
}
Expand Down
6 changes: 5 additions & 1 deletion src/server/injected/injectedScript.ts
Expand Up @@ -146,7 +146,11 @@ export class InjectedScript {
}

extend(source: string, params: any): any {
const constrFunction = global.eval(source);
const constrFunction = global.eval(`
(() => {
${source}
return pwExport;
})()`);
return new constrFunction(this, params);
}

Expand Down
9 changes: 6 additions & 3 deletions src/server/injected/injectedScript.webpack.config.js
Expand Up @@ -16,11 +16,11 @@

const path = require('path');
const InlineSource = require('./webpack-inline-source-plugin.js');

/** @type {import('webpack').Configuration} */
module.exports = {
entry: path.join(__dirname, 'injectedScript.ts'),
devtool: 'source-map',
mode: 'development',
mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
devtool: false,
module: {
rules: [
{
Expand All @@ -38,6 +38,9 @@ module.exports = {
},
output: {
filename: 'injectedScriptSource.js',
libraryTarget: 'var',
libraryExport: 'default',
library: 'pwExport',
path: path.resolve(__dirname, '../../../lib/server/injected/packed')
},
plugins: [
Expand Down
7 changes: 5 additions & 2 deletions src/server/injected/utilityScript.webpack.config.js
Expand Up @@ -17,10 +17,11 @@
const path = require('path');
const InlineSource = require('./webpack-inline-source-plugin.js');

/** @type {import('webpack').Configuration} */
module.exports = {
entry: path.join(__dirname, 'utilityScript.ts'),
devtool: 'source-map',
mode: 'development',
mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
devtool: false,
module: {
rules: [
{
Expand All @@ -38,6 +39,8 @@ module.exports = {
},
output: {
libraryTarget: 'var',
library: 'pwExport',
libraryExport: 'default',
filename: 'utilityScriptSource.js',
path: path.resolve(__dirname, '../../../lib/server/injected/packed')
},
Expand Down
11 changes: 4 additions & 7 deletions src/server/injected/webpack-inline-source-plugin.js
Expand Up @@ -22,15 +22,12 @@ module.exports = class InlineSource {
this.outFile = outFile;
}

/**
* @param {import('webpack').Compiler} compiler
*/
apply(compiler) {
compiler.hooks.emit.tapAsync('InlineSource', (compilation, callback) => {
let source = compilation.assets[path.basename(this.outFile).replace('.ts', '.js')].source();
const lastLine = source.split('\n').pop();
if (lastLine.startsWith('//# sourceMappingURL'))
source = source.substring(0, source.length - lastLine.length - 1);
if (source.endsWith(';'))
source = source.substring(0, source.length - 1);
source = '(' + source + ').default';
const source = compilation.assets[path.basename(this.outFile).replace('.ts', '.js')].source();
fs.mkdirSync(path.dirname(this.outFile), { recursive: true });
const newSource = 'export const source = ' + JSON.stringify(source) + ';';
fs.writeFileSync(this.outFile, newSource);
Expand Down
6 changes: 5 additions & 1 deletion src/server/javascript.ts
Expand Up @@ -64,7 +64,11 @@ export class ExecutionContext {

utilityScript(): Promise<JSHandle<UtilityScript>> {
if (!this._utilityScriptPromise) {
const source = `new (${utilityScriptSource.source})()`;
const source = `
(() => {
${utilityScriptSource.source}
return new pwExport();
})();`;
this._utilityScriptPromise = this._delegate.rawEvaluate(source).then(objectId => new JSHandle(this, 'object', objectId));
}
return this._utilityScriptPromise;
Expand Down
4 changes: 4 additions & 0 deletions test/page-evaluate.spec.ts
Expand Up @@ -554,3 +554,7 @@ it('should not use toJSON in jsonValue', async ({ page }) => {
const resultHandle = await page.evaluateHandle(() => ({ toJSON: () => 'string', data: 'data' }));
expect(await resultHandle.jsonValue()).toEqual({ data: 'data', toJSON: {} });
});

it('should not expose the injected script export', async ({ page }) => {
expect(await page.evaluate('typeof pwExport === "undefined"')).toBe(true);
});
10 changes: 8 additions & 2 deletions utils/build/build.js
Expand Up @@ -40,7 +40,10 @@ function runWatch() {

const spawns = [];
for (const step of steps)
spawns.push(child_process.spawn(step.command, step.args, { stdio: 'inherit', shell: step.shell }));
spawns.push(child_process.spawn(step.command, step.args, { stdio: 'inherit', shell: step.shell, env: {
...process.env,
...step.env,
} }));
process.on('exit', () => spawns.forEach(s => s.kill()));
for (const onChange of onChanges)
runOnChanges(onChange.inputs, onChange.script);
Expand Down Expand Up @@ -72,8 +75,11 @@ const webPackFiles = [
for (const file of webPackFiles) {
steps.push({
command: 'npx',
args: ['webpack', '--config', filePath(file), ...(watchMode ? ['--watch', '--silent', '--mode', 'development'] : [])],
args: ['webpack', '--config', filePath(file), ...(watchMode ? ['--watch', '--silent'] : [])],
shell: true,
env: {
NODE_ENV: watchMode ? 'development' : 'production'
}
});
}

Expand Down

0 comments on commit 31d980f

Please sign in to comment.