Skip to content

Commit

Permalink
fix(mc-scripts): dynamically change public path of assets on runtime …
Browse files Browse the repository at this point in the history
…for cdnUrl
  • Loading branch information
emmenko committed Apr 26, 2022
1 parent 08386a7 commit 33ffaef
Show file tree
Hide file tree
Showing 8 changed files with 74 additions and 5 deletions.
11 changes: 11 additions & 0 deletions packages/mc-html-template/html-scripts/public-path.js
@@ -0,0 +1,11 @@
window.__dynamicImportHandler__ = function (importer) {
return `${window.app.cdnUrl.replace(/\/$/, '')}/${importer.replace(
/^(\.\/)?/,
''
)}`;
};
window.__dynamicImportPreload__ = function (preloads) {
return preloads.map(
(preload) => `${window.app.cdnUrl.replace(/\/$/, '')}/${preload}`
);
};
1 change: 1 addition & 0 deletions packages/mc-html-template/src/index.js
Expand Up @@ -2,3 +2,4 @@ exports.compileHtml = require('./compile-html');
exports.generateTemplate = require('./generate-template');
exports.processHeaders = require('./process-headers');
exports.replaceHtmlPlaceholders = require('./utils/replace-html-placeholders');
exports.htmlScripts = require('./load-html-scripts');
1 change: 1 addition & 0 deletions packages/mc-html-template/src/load-html-scripts.js
Expand Up @@ -26,4 +26,5 @@ const loadScriptAsString = (fileName) => {
module.exports = {
dataLayer: loadScriptAsString('data-layer.js'),
loadingScreen: loadScriptAsString('loading-screen.js'),
publicPath: loadScriptAsString('public-path.js'),
};
3 changes: 2 additions & 1 deletion packages/mc-html-template/src/process-headers.js
Expand Up @@ -46,11 +46,12 @@ const processHeaders = (applicationConfig) => {
// List hashes for injected inline scripts.
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src
const htmlScriptsHashes = [
createAssetHash(htmlScripts.dataLayer),
createAssetHash(htmlScripts.loadingScreen),
createAssetHash(
`window.app = ${sanitizeAppEnvironment(applicationConfig.env)};`
),
createAssetHash(htmlScripts.publicPath),
createAssetHash(htmlScripts.dataLayer),
];

// // List hashes for injected inline styles.
Expand Down
1 change: 1 addition & 0 deletions packages/mc-scripts/package.json
Expand Up @@ -76,6 +76,7 @@
"thread-loader": "3.0.4",
"url": "^0.11.0",
"vite": "2.9.1",
"vite-plugin-dynamic-publicpath": "1.1.2",
"webpack": "5.72.0",
"webpack-bundle-analyzer": "4.5.0",
"webpack-dev-server": "4.8.1",
Expand Down
29 changes: 27 additions & 2 deletions packages/mc-scripts/src/commands/build-vite.js
@@ -1,10 +1,13 @@
/* eslint-disable react-hooks/rules-of-hooks */
const fs = require('fs-extra');
const path = require('path');
const { build } = require('vite');
const pluginGraphql = require('@rollup/plugin-graphql');
const pluginReact = require('@vitejs/plugin-react').default;
const { useDynamicPublicPath } = require('vite-plugin-dynamic-publicpath');
const {
generateTemplate,
htmlScripts,
} = require('@commercetools-frontend/mc-html-template');
const {
packageLocation: applicationStaticAssetsPath,
Expand All @@ -23,10 +26,23 @@ const pluginCustomApplication = () => {
// Ensure to use the `cdnUrl` value when loading the entry point.
// NOTE: with Webpack this is done by setting the `__webpack_public_path__`.
const html = rawHtml.replace(
new RegExp(`<script type="module"(.*) src="/(.*)">`, 'g'),
new RegExp(`<script type="module"(.*) src="(.*)">`, 'g'),
`<script type="module"$1 src="__CDN_URL__$2">`
);
return html;

return {
html,
tags: [
{
tag: 'script',
// Inject the functions to dynamically change the public path.
// This is also used for the `cdnUrl` and is the equivalent
// of Webpack's `__webpack_public_path__`.
children: htmlScripts.publicPath,
injectTo: 'body',
},
],
};
},
};
};
Expand All @@ -51,6 +67,7 @@ const execute = async () => {
await build({
configFile: false,
root: paths.appRoot,
base: '', // <-- Very important, otherwise asset URLs start with `/`.
define: {
'process.env.DEBUG': JSON.stringify(false),
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
Expand Down Expand Up @@ -78,6 +95,14 @@ const execute = async () => {
},
}),
pluginCustomApplication(),
// This plugin allows to change the public path on runtime.
// This is the equivalent of Webpack's `__webpack_public_path__`.
// See original issue: https://github.com/vitejs/vite/issues/3522#issuecomment-874377284
useDynamicPublicPath({
dynamicImportHandler: 'window.__dynamicImportHandler__',
dynamicImportPreload: 'window.__dynamicImportPreload__',
assetsBase: '.',
}),
],
});

Expand Down
16 changes: 14 additions & 2 deletions packages/mc-scripts/src/config/application-runtime.js
Expand Up @@ -2,5 +2,17 @@
// Dynamically inject webpack `publicPath`, for resolving assets locations.
// https://webpack.js.org/guides/public-path/#on-the-fly
// https://webpack.js.org/configuration/output/#output-publicpath
if (process.env.NODE_ENV !== 'test')
__webpack_public_path__ = `${window.app.cdnUrl.replace(/\/$/, '')}/`;
if (process.env.NODE_ENV !== 'test') {
const basePath = `${window.app.cdnUrl.replace(/\/$/, '')}/`;

// Webpack
__webpack_public_path__ = basePath;

// Vite
window.__dynamicImportHandler__ = function (importer) {
return basePath + importer;
};
window.__dynamicImportPreload__ = function (preloads) {
return preloads.map((preload) => basePath + preload);
};
}
17 changes: 17 additions & 0 deletions yarn.lock
Expand Up @@ -3055,6 +3055,7 @@ __metadata:
thread-loader: 3.0.4
url: ^0.11.0
vite: 2.9.1
vite-plugin-dynamic-publicpath: 1.1.2
webpack: 5.72.0
webpack-bundle-analyzer: 4.5.0
webpack-dev-server: 4.8.1
Expand Down Expand Up @@ -16247,6 +16248,13 @@ __metadata:
languageName: node
linkType: hard

"es-module-lexer@npm:^0.6.0":
version: 0.6.0
resolution: "es-module-lexer@npm:0.6.0"
checksum: ef04832d0f118e07c5aafc3824f274df380e9f86915a2d665884d9498f580b1f5607bc633504460a6c6247b7689aaa774b024d6733de28614d1fab72991a6fc3
languageName: node
linkType: hard

"es-module-lexer@npm:^0.9.0":
version: 0.9.3
resolution: "es-module-lexer@npm:0.9.3"
Expand Down Expand Up @@ -34370,6 +34378,15 @@ __metadata:
languageName: node
linkType: hard

"vite-plugin-dynamic-publicpath@npm:1.1.2":
version: 1.1.2
resolution: "vite-plugin-dynamic-publicpath@npm:1.1.2"
dependencies:
es-module-lexer: ^0.6.0
checksum: c631149bb006af3e5a6c00ef4cf891b33cc1e6d7839a5b940f671e798a8382196c5fe3a4782f047f7f37a65a76691a8e3c2eab62117be0a685f2287a32a47771
languageName: node
linkType: hard

"vite@npm:2.9.1":
version: 2.9.1
resolution: "vite@npm:2.9.1"
Expand Down

0 comments on commit 33ffaef

Please sign in to comment.