Skip to content

Commit

Permalink
misc(build): convert to ES modules (#13967)
Browse files Browse the repository at this point in the history
  • Loading branch information
connorjclark authored May 6, 2022
1 parent d9929e0 commit e107194
Show file tree
Hide file tree
Showing 26 changed files with 224 additions and 186 deletions.
28 changes: 28 additions & 0 deletions build/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* @license Copyright 2022 The Lighthouse Authors. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/

module.exports = {
rules: {
// TODO(esmodules): move to root eslint when all code is ESM
// or when this is resolved: https://github.com/import-js/eslint-plugin-import/issues/2214
'import/order': [2, {
'groups': [
'builtin',
'external',
['sibling', 'parent'],
'index',
'object',
'type',
],
'newlines-between': 'always',
}],
'import/group-exports': 2,
'import/exports-last': 2,
},
parserOptions: {
sourceType: 'module',
},
};
52 changes: 29 additions & 23 deletions build/build-bundle.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,35 @@
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';

/**
* @fileoverview Script to bundle lighthouse entry points so that they can be run
* in the browser (as long as they have access to a debugger protocol Connection).
*/

const fs = require('fs');
const path = require('path');
const rollup = require('rollup');
const rollupPlugins = require('./rollup-plugins.js');
const Runner = require('../lighthouse-core/runner.js');
const {LH_ROOT} = require('../root.js');
import fs from 'fs';
import path from 'path';
import {execSync} from 'child_process';

const COMMIT_HASH = require('child_process')
.execSync('git rev-parse HEAD')
.toString().trim();
import esMain from 'es-main';
import {rollup} from 'rollup';
// @ts-expect-error: plugin has no types.
import PubAdsPlugin from 'lighthouse-plugin-publisher-ads/plugin.js';

import * as rollupPlugins from './rollup-plugins.js';
import Runner from '../lighthouse-core/runner.js';
import {LH_ROOT, readJson} from '../root.js';
import {createCommonjsRefs} from '../lighthouse-core/scripts/esm-utils.js';

const {require} = createCommonjsRefs(import.meta);

/** The commit hash for the current HEAD. */
const COMMIT_HASH = execSync('git rev-parse HEAD').toString().trim();

// HACK: manually include the lighthouse-plugin-publisher-ads audits.
/** @type {Array<string>} */
// @ts-expect-error
const pubAdsAudits = require('lighthouse-plugin-publisher-ads/plugin.js').audits.map(a => a.path);
const pubAdsAudits = PubAdsPlugin.audits.map(a => a.path);

/** @param {string} file */
const isDevtools = file =>
Expand All @@ -42,7 +49,7 @@ const today = (() => {
const day = new Intl.DateTimeFormat('en', {day: '2-digit'}).format(date);
return `${month} ${day} ${year}`;
})();
const pkg = JSON.parse(fs.readFileSync(LH_ROOT + '/package.json', 'utf-8'));
const pkg = readJson(`${LH_ROOT}/package.json`);
const banner = `
/**
* Lighthouse v${pkg.version} ${COMMIT_HASH} (${today})
Expand All @@ -62,7 +69,7 @@ const banner = `
* @param {{minify: boolean}=} opts
* @return {Promise<void>}
*/
async function build(entryPath, distPath, opts = {minify: true}) {
async function buildBundle(entryPath, distPath, opts = {minify: true}) {
if (fs.existsSync(LH_ROOT + '/lighthouse-logger/node_modules')) {
throw new Error('delete `lighthouse-logger/node_modules` because it messes up rollup bundle');
}
Expand Down Expand Up @@ -117,9 +124,9 @@ async function build(entryPath, distPath, opts = {minify: true}) {
}

shimsObj[require.resolve('../package.json')] =
`export const version = ${JSON.stringify(require('../package.json').version)}`;
`export const version = '${pkg.version}';`;

const bundle = await rollup.rollup({
const bundle = await rollup({
input: entryPath,
context: 'globalThis',
plugins: [
Expand Down Expand Up @@ -214,19 +221,18 @@ async function cli(argv) {
// Take paths relative to cwd and build.
const [entryPath, distPath] = argv.slice(2)
.map(filePath => path.resolve(process.cwd(), filePath));
await build(entryPath, distPath);
await buildBundle(entryPath, distPath);
}

// Test if called from the CLI or as a module.
if (require.main === module) {
if (esMain(import.meta)) {
cli(process.argv).catch(err => {
console.error(err);
process.exit(1);
});
} else {
module.exports = {
/** The commit hash for the current HEAD. */
COMMIT_HASH,
build,
};
}

export {
COMMIT_HASH,
buildBundle,
};
12 changes: 7 additions & 5 deletions build/build-cdt-lib.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';


/* eslint-disable no-console */

const fs = require('fs');
const ts = require('typescript');
const {LH_ROOT} = require('../root.js');
import fs from 'fs';

import ts from 'typescript';

import {LH_ROOT} from '../root.js';

const outDir = `${LH_ROOT}/lighthouse-core/lib/cdt/generated`;
const files = {
Expand Down Expand Up @@ -86,7 +88,7 @@ for (const [inFilename, outFilename] of Object.entries(files)) {
}).toString(),
// Add some types.
// eslint-disable-next-line max-len
'mappings() {': '/** @return {Array<{lineNumber: number, columnNumber: number, sourceURL?: string, sourceLineNumber, sourceColumnNumber: number, name?: string, lastColumnNumber?: number}>} */\nmappings() {',
'mappings() {': '/** @return {Array<{lineNumber: number, columnNumber: number, sourceURL?: string, sourceLineNumber: number, sourceColumnNumber: number, name?: string, lastColumnNumber?: number}>} */\nmappings() {',
};

// Verify that all the above code is present.
Expand Down
17 changes: 9 additions & 8 deletions build/build-dt-report-resources.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';

const rollup = require('rollup');
const rollupPlugins = require('./rollup-plugins.js');
const fs = require('fs');
const path = require('path');
const assert = require('assert').strict;
const {LH_ROOT} = require('../root.js');
import fs from 'fs';
import path from 'path';
import {strict as assert} from 'assert';

import {rollup} from 'rollup';

import * as rollupPlugins from './rollup-plugins.js';
import {LH_ROOT} from '../root.js';

const distDir = path.join(LH_ROOT, 'dist', 'dt-report-resources');
const bundleOutFile = `${distDir}/report-generator.mjs`;
Expand All @@ -30,7 +31,7 @@ fs.mkdirSync(distDir, {recursive: true});
writeFile('report-generator.mjs.d.ts', 'export {}');

async function buildReportGenerator() {
const bundle = await rollup.rollup({
const bundle = await rollup({
input: 'report/generator/report-generator.js',
plugins: [
rollupPlugins.shim({
Expand Down
22 changes: 11 additions & 11 deletions build/build-extension.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';

const fs = require('fs');
const mkdir = fs.promises.mkdir;
const archiver = require('archiver');
const cpy = require('cpy');
const rollup = require('rollup');
const rollupPlugins = require('./rollup-plugins.js');
const {LH_ROOT} = require('../root.js');
import fs from 'fs';

import archiver from 'archiver';
import cpy from 'cpy';
import {rollup} from 'rollup';

import * as rollupPlugins from './rollup-plugins.js';
import {LH_ROOT, readJson} from '../root.js';

const argv = process.argv.slice(2);
const browserBrand = argv[0];
Expand All @@ -23,13 +23,13 @@ const sourceDir = `${LH_ROOT}/clients/extension`;
const distDir = `${LH_ROOT}/dist/extension-${browserBrand}`;
const packagePath = `${distDir}/../extension-${browserBrand}-package`;

const manifestVersion = require(`${sourceDir}/manifest.json`).version;
const manifestVersion = readJson(`${sourceDir}/manifest.json`).version;

/**
* Bundle and minify entry point.
*/
async function buildEntryPoint() {
const bundle = await rollup.rollup({
const bundle = await rollup({
input: `${sourceDir}/scripts/${sourceName}`,
plugins: [
rollupPlugins.shim({
Expand Down Expand Up @@ -70,7 +70,7 @@ function copyAssets() {
* @return {Promise<void>}
*/
async function packageExtension() {
await mkdir(packagePath, {recursive: true});
await fs.promises.mkdir(packagePath, {recursive: true});

return new Promise((resolve, reject) => {
const archive = archiver('zip', {
Expand Down
21 changes: 11 additions & 10 deletions build/build-lightrider-bundles.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';

const rollup = require('rollup');
const rollupPlugins = require('./rollup-plugins.js');
const fs = require('fs');
const path = require('path');
const bundleBuilder = require('./build-bundle.js');
const {LH_ROOT} = require('../root.js');
import fs from 'fs';
import path from 'path';

import {rollup} from 'rollup';

import * as rollupPlugins from './rollup-plugins.js';
import {buildBundle} from './build-bundle.js';
import {LH_ROOT} from '../root.js';

const distDir = path.join(LH_ROOT, 'dist', 'lightrider');
const sourceDir = path.join(LH_ROOT, 'clients', 'lightrider');
Expand All @@ -23,11 +24,11 @@ fs.mkdirSync(distDir, {recursive: true});
function buildEntryPoint() {
const inFile = `${sourceDir}/${entrySourceName}`;
const outFile = `${distDir}/${entryDistName}`;
return bundleBuilder.build(inFile, outFile, {minify: false});
return buildBundle(inFile, outFile, {minify: false});
}

async function buildReportGenerator() {
const bundle = await rollup.rollup({
const bundle = await rollup({
input: 'report/generator/report-generator.js',
plugins: [
rollupPlugins.shim({
Expand All @@ -48,7 +49,7 @@ async function buildReportGenerator() {
}

async function buildStaticServerBundle() {
const bundle = await rollup.rollup({
const bundle = await rollup({
input: 'lighthouse-cli/test/fixtures/static-server.js',
plugins: [
rollupPlugins.shim({
Expand Down
14 changes: 8 additions & 6 deletions build/build-report-components.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';

/**
* @typedef CompiledComponent
Expand All @@ -13,9 +12,12 @@
* @property {string} functionCode
*/

const fs = require('fs');
const jsdom = require('jsdom');
const {LH_ROOT} = require('../root.js');
import fs from 'fs';

import jsdom from 'jsdom';
import esMain from 'es-main';

import {LH_ROOT} from '../root.js';

const html = fs.readFileSync(LH_ROOT + '/report/assets/templates.html', 'utf-8');
const {window} = new jsdom.JSDOM(html);
Expand Down Expand Up @@ -213,11 +215,11 @@ ${makeGenericCreateComponentFunctionCode(compiledTemplates)}
fs.writeFileSync(LH_ROOT + '/report/renderer/components.js', code);
}

if (require.main === module) {
if (esMain(import.meta)) {
main().catch(err => {
console.error(err);
process.exit(1);
});
}

module.exports = {normalizeTextNodeText};
export {normalizeTextNodeText};
Loading

0 comments on commit e107194

Please sign in to comment.