Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: added plugin for automatic importmap generation #393

Merged
merged 2 commits into from
Jul 21, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 95 additions & 0 deletions generate-import-map.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import path from "path";
import fs from "fs";

/**
* When assets are deployed to Theming Center, their file name is changed and this
* breaks the rollup bundles, where bundled files are referencing each other with
* relative paths (e.g. file a.js has an `import something from "./b.js"`)
*
* This plugin solves the issue by creating an importmap to be used in the browser,
* specifically:
* - it replaces relative imports with bare imports (`import something from "./b.js"`
* is replaced with `import something from "b"`)
* - it creates an importmap that maps each bare import to the asset file, using the
* Curlybars asset helper. This import map is then injected into the document_head.hbs
* template and used by the browser to resolve the bare imports.
*
* Note: you need to have an importmap in the document_head that gets replaced
* after each build. The first time you can just put an empty importmap:
* <script type="importmap"></script>
* @returns {import("rollup").Plugin}
*/
export function generateImportMap() {
return {
name: "rollup-plugin-generate-import-map",
writeBundle({ dir }, bundle) {
const outputChunksNames = Object.keys(bundle);
luis-almeida marked this conversation as resolved.
Show resolved Hide resolved
const importMap = { imports: {} };

for (const chunkName of outputChunksNames) {
relativeToBareImports(chunkName, outputChunksNames, dir);
importMap.imports[getBareName(chunkName)] = `{{asset '${chunkName}'}}`;
}

injectImportMap(importMap);
},
};
}

/**
* Replace relative imports with bare imports
* @param {string} chunkName Name of the current chunk
* @param {string[]} outputChunksNames Array of chunks generated during the build
* @param {string} outputPath Path of the output directory
*/
function relativeToBareImports(chunkName, outputChunksNames, outputPath) {
luis-almeida marked this conversation as resolved.
Show resolved Hide resolved
const chunkPath = path.resolve(outputPath, chunkName);

let content = fs.readFileSync(chunkPath, "utf-8");

for (const chunkName of outputChunksNames) {
const bare = getBareName(chunkName);
content = content.replaceAll(`'./${chunkName}'`, `'${bare}'`);
}

fs.writeFileSync(chunkPath, content, "utf-8");
}

/**
* Injects the importmap in the document_head.hbs template, replacing the existing one
* @param {object} importMap
*/
function injectImportMap(importMap) {
const headTemplatePath = path.resolve("templates", "document_head.hbs");
const content = fs.readFileSync(headTemplatePath, "utf-8");
const importMapStart = content.indexOf(`<script type="importmap">`);
const importMapEnd = content.indexOf(`</script>`, importMapStart);

if (importMapStart === -1 || importMapEnd === -1) {
throw new Error(
`Cannot inject importmap in templates/document_head.hbs. Please provide an empty importmap like <script type="importmap"></script>`
);
}

const existingImportMap = content.substring(
importMapStart,
importMapEnd + `</script>`.length
);

const newImportMap = `<script type="importmap">
${JSON.stringify(importMap, null, 2)}
</script>`;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: to keep the code alignment [].join('\n') is also an option.


const newContent = content.replace(existingImportMap, newImportMap);

fs.writeFileSync(headTemplatePath, newContent, "utf-8");
}

/**
*
* @param {string} chunkName
* @returns {string}
*/
function getBareName(chunkName) {
return chunkName.replace(".js", "");
}
35 changes: 2 additions & 33 deletions rollup.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { nodeResolve } from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import typescript from "@rollup/plugin-typescript";
import replace from "@rollup/plugin-replace";
import { generateImportMap } from "./generate-import-map.mjs"
import { defineConfig } from "rollup";

export default defineConfig([
Expand Down Expand Up @@ -42,42 +43,10 @@ export default defineConfig([
preventAssignment: true,
"process.env.NODE_ENV": '"production"',
}),
replaceVendorImport(),
generateImportMap(),
],
watch: {
clearScreen: false,
},
},
]);

/*
TODO: Find a better way to do this

This is required to make import maps works on production.

All node deps are bundled in the assets/vendor.js file, and normally rollup
writes `import {...} from "./vendor.js"`.

We want to use import maps to remap "./vendor.js" to the `vendor.js` theme asset,
but for some reasons in this case the browser is trying to load a local script instead
of following the import map.

Instead if we change `./vendor.js` to `vendor` it works and the browser load the vendor.js asset.
*/
const mappedAssets = {
"./vendor.js": "vendor",
"./shared.js": "shared",
};

function replaceVendorImport() {
return {
name: "rollup-plugin-replace-vendor-import",
renderChunk(code) {
let res = code;
for (const [key, value] of Object.entries(mappedAssets)) {
res = res.replaceAll(`from '${key}'`, `from '${value}'`);
}
return res;
},
};
}
14 changes: 7 additions & 7 deletions templates/document_head.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
<!-- See buildClearSearchButton() in script.js -->
<script type="text/javascript">window.searchClearButtonLabelLocalized = "{{t 'search_clear'}}";</script>
<script type="importmap">
{
"imports": {
"vendor": "{{asset 'vendor.js'}}",
"shared": "{{asset 'shared.js'}}",
"new-request-form": "{{asset 'new-request-form.js'}}"
}
}
{
"imports": {
"new-request-form": "{{asset 'new-request-form.js'}}",
"shared": "{{asset 'shared.js'}}",
"vendor": "{{asset 'vendor.js'}}"
}
}
</script>
<script type="module">
import { setupGardenTheme } from "shared";
Expand Down