Skip to content

Commit

Permalink
[7.x] [kbn/optimizer] update public path before imports (#67561) (#67807
Browse files Browse the repository at this point in the history
)

Co-authored-by: spalger <spalger@users.noreply.github.com>
  • Loading branch information
Spencer and spalger committed Jun 1, 2020
1 parent 5b0cfad commit 586e174
Show file tree
Hide file tree
Showing 8 changed files with 69 additions and 18 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
body {
color: green;
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
*/

import './legacy/styles.scss';
import './index.scss';
import { fooLibFn } from '../../foo/public/index';
export * from './lib';
export { fooLibFn };

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,17 @@ import { inspect } from 'util';
import cpy from 'cpy';
import del from 'del';
import { toArray, tap } from 'rxjs/operators';
import { createAbsolutePathSerializer, ToolingLog, REPO_ROOT } from '@kbn/dev-utils';
import { ToolingLog, REPO_ROOT } from '@kbn/dev-utils';
import { runOptimizer, OptimizerConfig, OptimizerUpdate, logOptimizerState } from '@kbn/optimizer';

const TMP_DIR = Path.resolve(__dirname, '../__fixtures__/__tmp__');
const MOCK_REPO_SRC = Path.resolve(__dirname, '../__fixtures__/mock_repo');
const MOCK_REPO_DIR = Path.resolve(TMP_DIR, 'mock_repo');

expect.addSnapshotSerializer(createAbsolutePathSerializer(REPO_ROOT));
expect.addSnapshotSerializer({
print: (value: string) => value.split(REPO_ROOT).join('<absolute path>').replace(/\\/g, '/'),
test: (value: any) => typeof value === 'string' && value.includes(REPO_ROOT),
});

beforeAll(async () => {
await del(TMP_DIR);
Expand Down Expand Up @@ -135,28 +138,30 @@ it('builds expected bundles, saves bundle counts to metadata', async () => {
const foo = config.bundles.find((b) => b.id === 'foo')!;
expect(foo).toBeTruthy();
foo.cache.refresh();
expect(foo.cache.getModuleCount()).toBe(4);
expect(foo.cache.getModuleCount()).toBe(5);
expect(foo.cache.getReferencedFiles()).toMatchInlineSnapshot(`
Array [
<absolute path>/packages/kbn-optimizer/src/__fixtures__/__tmp__/mock_repo/plugins/foo/public/async_import.ts,
<absolute path>/packages/kbn-optimizer/src/__fixtures__/__tmp__/mock_repo/plugins/foo/public/ext.ts,
<absolute path>/packages/kbn-optimizer/src/__fixtures__/__tmp__/mock_repo/plugins/foo/public/index.ts,
<absolute path>/packages/kbn-optimizer/src/__fixtures__/__tmp__/mock_repo/plugins/foo/public/lib.ts,
<absolute path>/packages/kbn-ui-shared-deps/public_path_module_creator.js,
]
`);

const bar = config.bundles.find((b) => b.id === 'bar')!;
expect(bar).toBeTruthy();
bar.cache.refresh();
expect(bar.cache.getModuleCount()).toBe(
// code + styles + style/css-loader runtimes
15
// code + styles + style/css-loader runtimes + public path updater
21
);

expect(bar.cache.getReferencedFiles()).toMatchInlineSnapshot(`
Array [
<absolute path>/node_modules/css-loader/package.json,
<absolute path>/node_modules/style-loader/package.json,
<absolute path>/packages/kbn-optimizer/src/__fixtures__/__tmp__/mock_repo/plugins/bar/public/index.scss,
<absolute path>/packages/kbn-optimizer/src/__fixtures__/__tmp__/mock_repo/plugins/bar/public/index.ts,
<absolute path>/packages/kbn-optimizer/src/__fixtures__/__tmp__/mock_repo/plugins/bar/public/legacy/styles.scss,
<absolute path>/packages/kbn-optimizer/src/__fixtures__/__tmp__/mock_repo/plugins/bar/public/lib.ts,
Expand All @@ -165,6 +170,7 @@ it('builds expected bundles, saves bundle counts to metadata', async () => {
<absolute path>/packages/kbn-optimizer/src/__fixtures__/__tmp__/mock_repo/plugins/foo/public/index.ts,
<absolute path>/packages/kbn-optimizer/src/__fixtures__/__tmp__/mock_repo/plugins/foo/public/lib.ts,
<absolute path>/packages/kbn-optimizer/src/__fixtures__/__tmp__/mock_repo/src/legacy/ui/public/icon.svg,
<absolute path>/packages/kbn-ui-shared-deps/public_path_module_creator.js,
]
`);
});
Expand Down Expand Up @@ -205,6 +211,7 @@ it('uses cache on second run and exist cleanly', async () => {
*/
const expectFileMatchesSnapshotWithCompression = (filePath: string, snapshotLabel: string) => {
const raw = Fs.readFileSync(Path.resolve(MOCK_REPO_DIR, filePath), 'utf8');

expect(raw).toMatchSnapshot(snapshotLabel);

// Verify the brotli variant matches
Expand Down
24 changes: 15 additions & 9 deletions packages/kbn-optimizer/src/worker/webpack.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
* under the License.
*/

import Fs from 'fs';
import Path from 'path';

import normalizePath from 'normalize-path';
Expand Down Expand Up @@ -84,12 +85,17 @@ function dynamicExternals(bundle: Bundle, context: string, request: string) {
}

export function getWebpackConfig(bundle: Bundle, worker: WorkerConfig) {
const extensions = ['.js', '.ts', '.tsx', '.json'];
const entryExtension = extensions.find((ext) =>
Fs.existsSync(Path.resolve(bundle.contextDir, bundle.entry) + ext)
);

const commonConfig: webpack.Configuration = {
node: { fs: 'empty' },
context: bundle.contextDir,
cache: true,
entry: {
[bundle.id]: bundle.entry,
[bundle.id]: `${bundle.entry}${entryExtension}`,
},

devtool: worker.dist ? false : '#cheap-source-map',
Expand Down Expand Up @@ -141,13 +147,6 @@ export function getWebpackConfig(bundle: Bundle, worker: WorkerConfig) {
],

rules: [
{
include: Path.join(bundle.contextDir, bundle.entry),
loader: UiSharedDeps.publicPathLoader,
options: {
key: bundle.id,
},
},
{
test: /\.css$/,
include: /node_modules/,
Expand Down Expand Up @@ -278,6 +277,13 @@ export function getWebpackConfig(bundle: Bundle, worker: WorkerConfig) {
},
},
},
{
include: [`${Path.resolve(bundle.contextDir, bundle.entry)}${entryExtension}`],
loader: UiSharedDeps.publicPathLoader,
options: {
key: bundle.id,
},
},
{
test: /\.(html|md|txt|tmpl)$/,
use: {
Expand All @@ -288,7 +294,7 @@ export function getWebpackConfig(bundle: Bundle, worker: WorkerConfig) {
},

resolve: {
extensions: ['.js', '.ts', '.tsx', '.json'],
extensions,
mainFields: ['browser', 'main'],
alias: {
tinymath: require.resolve('tinymath/lib/tinymath.es5.js'),
Expand Down
2 changes: 2 additions & 0 deletions packages/kbn-ui-shared-deps/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@
"devDependencies": {
"@kbn/babel-preset": "1.0.0",
"@kbn/dev-utils": "1.0.0",
"loader-utils": "^1.2.3",
"val-loader": "^1.1.1",
"css-loader": "^3.4.2",
"del": "^5.1.0",
"webpack": "^4.41.5"
Expand Down
10 changes: 9 additions & 1 deletion packages/kbn-ui-shared-deps/public_path_loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,15 @@
* under the License.
*/

const Qs = require('querystring');
const { stringifyRequest } = require('loader-utils');

const VAL_LOADER = require.resolve('val-loader');
const MODULE_CREATOR = require.resolve('./public_path_module_creator');

module.exports = function (source) {
const options = this.query;
return `__webpack_public_path__ = window.__kbnPublicPath__['${options.key}'];${source}`;
const valOpts = Qs.stringify({ key: options.key });
const req = `${VAL_LOADER}?${valOpts}!${MODULE_CREATOR}`;
return `import ${stringifyRequest(this, req)};${source}`;
};
24 changes: 24 additions & 0 deletions packages/kbn-ui-shared-deps/public_path_module_creator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you 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 = function ({ key }) {
return {
code: `__webpack_public_path__ = window.__kbnPublicPath__['${key}']`,
};
};

0 comments on commit 586e174

Please sign in to comment.