From 586e174785395c544a78f55bd6bff5afa7e8bb6c Mon Sep 17 00:00:00 2001 From: Spencer Date: Mon, 1 Jun 2020 13:51:26 -0700 Subject: [PATCH] [7.x] [kbn/optimizer] update public path before imports (#67561) (#67807) Co-authored-by: spalger --- .../mock_repo/plugins/bar/public/index.scss | 3 +++ .../mock_repo/plugins/bar/public/index.ts | 1 + .../basic_optimization.test.ts.snap | 6 ++--- .../basic_optimization.test.ts | 17 +++++++++---- .../src/worker/webpack.config.ts | 24 ++++++++++++------- packages/kbn-ui-shared-deps/package.json | 2 ++ .../kbn-ui-shared-deps/public_path_loader.js | 10 +++++++- .../public_path_module_creator.js | 24 +++++++++++++++++++ 8 files changed, 69 insertions(+), 18 deletions(-) create mode 100644 packages/kbn-optimizer/src/__fixtures__/mock_repo/plugins/bar/public/index.scss create mode 100644 packages/kbn-ui-shared-deps/public_path_module_creator.js diff --git a/packages/kbn-optimizer/src/__fixtures__/mock_repo/plugins/bar/public/index.scss b/packages/kbn-optimizer/src/__fixtures__/mock_repo/plugins/bar/public/index.scss new file mode 100644 index 00000000000000..563d20e99ce82c --- /dev/null +++ b/packages/kbn-optimizer/src/__fixtures__/mock_repo/plugins/bar/public/index.scss @@ -0,0 +1,3 @@ +body { + color: green; +} diff --git a/packages/kbn-optimizer/src/__fixtures__/mock_repo/plugins/bar/public/index.ts b/packages/kbn-optimizer/src/__fixtures__/mock_repo/plugins/bar/public/index.ts index 817c4796562e82..7ddd10f4a388fb 100644 --- a/packages/kbn-optimizer/src/__fixtures__/mock_repo/plugins/bar/public/index.ts +++ b/packages/kbn-optimizer/src/__fixtures__/mock_repo/plugins/bar/public/index.ts @@ -18,6 +18,7 @@ */ import './legacy/styles.scss'; +import './index.scss'; import { fooLibFn } from '../../foo/public/index'; export * from './lib'; export { fooLibFn }; diff --git a/packages/kbn-optimizer/src/integration_tests/__snapshots__/basic_optimization.test.ts.snap b/packages/kbn-optimizer/src/integration_tests/__snapshots__/basic_optimization.test.ts.snap index fe0f75c05c6466..436a6843d51889 100644 --- a/packages/kbn-optimizer/src/integration_tests/__snapshots__/basic_optimization.test.ts.snap +++ b/packages/kbn-optimizer/src/integration_tests/__snapshots__/basic_optimization.test.ts.snap @@ -1,6 +1,6 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`builds expected bundles, saves bundle counts to metadata: 1 async bundle 1`] = `"(window[\\"foo_bundle_jsonpfunction\\"]=window[\\"foo_bundle_jsonpfunction\\"]||[]).push([[1],{3:function(module,exports,__webpack_require__){\\"use strict\\";Object.defineProperty(exports,\\"__esModule\\",{value:true});exports.foo=foo;function foo(){}}}]);"`; +exports[`builds expected bundles, saves bundle counts to metadata: 1 async bundle 1`] = `"(window[\\"foo_bundle_jsonpfunction\\"]=window[\\"foo_bundle_jsonpfunction\\"]||[]).push([[1],{4:function(module,exports,__webpack_require__){\\"use strict\\";Object.defineProperty(exports,\\"__esModule\\",{value:true});exports.foo=foo;function foo(){}}}]);"`; exports[`builds expected bundles, saves bundle counts to metadata: OptimizerConfig 1`] = ` OptimizerConfig { @@ -57,6 +57,6 @@ OptimizerConfig { } `; -exports[`builds expected bundles, saves bundle counts to metadata: bar bundle 1`] = `"var __kbnBundles__=typeof __kbnBundles__===\\"object\\"?__kbnBundles__:{};__kbnBundles__[\\"plugin/bar\\"]=function(modules){function webpackJsonpCallback(data){var chunkIds=data[0];var moreModules=data[1];var moduleId,chunkId,i=0,resolves=[];for(;i value.split(REPO_ROOT).join('').replace(/\\/g, '/'), + test: (value: any) => typeof value === 'string' && value.includes(REPO_ROOT), +}); beforeAll(async () => { await del(TMP_DIR); @@ -135,13 +138,14 @@ 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 [ /packages/kbn-optimizer/src/__fixtures__/__tmp__/mock_repo/plugins/foo/public/async_import.ts, /packages/kbn-optimizer/src/__fixtures__/__tmp__/mock_repo/plugins/foo/public/ext.ts, /packages/kbn-optimizer/src/__fixtures__/__tmp__/mock_repo/plugins/foo/public/index.ts, /packages/kbn-optimizer/src/__fixtures__/__tmp__/mock_repo/plugins/foo/public/lib.ts, + /packages/kbn-ui-shared-deps/public_path_module_creator.js, ] `); @@ -149,14 +153,15 @@ it('builds expected bundles, saves bundle counts to metadata', async () => { 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 [ /node_modules/css-loader/package.json, /node_modules/style-loader/package.json, + /packages/kbn-optimizer/src/__fixtures__/__tmp__/mock_repo/plugins/bar/public/index.scss, /packages/kbn-optimizer/src/__fixtures__/__tmp__/mock_repo/plugins/bar/public/index.ts, /packages/kbn-optimizer/src/__fixtures__/__tmp__/mock_repo/plugins/bar/public/legacy/styles.scss, /packages/kbn-optimizer/src/__fixtures__/__tmp__/mock_repo/plugins/bar/public/lib.ts, @@ -165,6 +170,7 @@ it('builds expected bundles, saves bundle counts to metadata', async () => { /packages/kbn-optimizer/src/__fixtures__/__tmp__/mock_repo/plugins/foo/public/index.ts, /packages/kbn-optimizer/src/__fixtures__/__tmp__/mock_repo/plugins/foo/public/lib.ts, /packages/kbn-optimizer/src/__fixtures__/__tmp__/mock_repo/src/legacy/ui/public/icon.svg, + /packages/kbn-ui-shared-deps/public_path_module_creator.js, ] `); }); @@ -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 diff --git a/packages/kbn-optimizer/src/worker/webpack.config.ts b/packages/kbn-optimizer/src/worker/webpack.config.ts index 3e978fff8e217b..1f2084c631d115 100644 --- a/packages/kbn-optimizer/src/worker/webpack.config.ts +++ b/packages/kbn-optimizer/src/worker/webpack.config.ts @@ -17,6 +17,7 @@ * under the License. */ +import Fs from 'fs'; import Path from 'path'; import normalizePath from 'normalize-path'; @@ -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', @@ -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/, @@ -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: { @@ -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'), diff --git a/packages/kbn-ui-shared-deps/package.json b/packages/kbn-ui-shared-deps/package.json index 541a70d930b614..ddbf1447dd6cfc 100644 --- a/packages/kbn-ui-shared-deps/package.json +++ b/packages/kbn-ui-shared-deps/package.json @@ -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" diff --git a/packages/kbn-ui-shared-deps/public_path_loader.js b/packages/kbn-ui-shared-deps/public_path_loader.js index fceebd6d6b3a1e..cdebdcb4f04227 100644 --- a/packages/kbn-ui-shared-deps/public_path_loader.js +++ b/packages/kbn-ui-shared-deps/public_path_loader.js @@ -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}`; }; diff --git a/packages/kbn-ui-shared-deps/public_path_module_creator.js b/packages/kbn-ui-shared-deps/public_path_module_creator.js new file mode 100644 index 00000000000000..1cb9989432178d --- /dev/null +++ b/packages/kbn-ui-shared-deps/public_path_module_creator.js @@ -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}']`, + }; +};