Skip to content

Commit

Permalink
refactor polyfills plugin to use require.resolve for node modules loc…
Browse files Browse the repository at this point in the history
…ation
  • Loading branch information
thescientist13 committed Sep 13, 2021
1 parent 0700796 commit 9f16979
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 8 deletions.
5 changes: 2 additions & 3 deletions packages/cli/src/lib/node-modules-utils.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
// ideally let NodeJS do the look up for us, but in the evant that fails
// do our best to resolve the file (helpful for theme pack testing and development)
// (where things are unpublished and routed around)
// defer to NodeJS to find where on disk a package is located using require.resolve
// and return the root absolute location
function getNodeModulesResolveLocationForPackageName(packageName) {
let nodeModulesUrl;

Expand Down
11 changes: 6 additions & 5 deletions packages/plugin-polyfills/src/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const fs = require('fs');
const { getNodeModulesResolveLocationForPackageName } = require('@greenwood/cli/src/lib/node-modules-utils');
const path = require('path');
const { ResourceInterface } = require('@greenwood/cli/src/lib/resource-interface');

Expand All @@ -12,16 +13,16 @@ class PolyfillsResource extends ResourceInterface {
}

async optimize(url, body) {
const polyfillPackageName = '@webcomponents/webcomponentsjs';
const filename = 'webcomponents-loader.js';
const nodeModuleRoot = 'node_modules/@webcomponents/webcomponentsjs';
const polyfillNodeModulesLocation = getNodeModulesResolveLocationForPackageName(polyfillPackageName);

return new Promise(async (resolve, reject) => {
try {
const cwd = process.cwd();
const { outputDir } = this.compilation.context;
const polyfillFiles = [
'webcomponents-loader.js',
...fs.readdirSync(path.join(process.cwd(), nodeModuleRoot, 'bundles')).map(file => {
...fs.readdirSync(path.join(polyfillNodeModulesLocation, 'bundles')).map(file => {
return `bundles/${file}`;
})
];
Expand All @@ -31,7 +32,7 @@ class PolyfillsResource extends ResourceInterface {
}

await Promise.all(polyfillFiles.map(async (file) => {
const from = path.join(cwd, nodeModuleRoot, file);
const from = path.join(polyfillNodeModulesLocation, file);
const to = path.join(outputDir, file);

return !fs.existsSync(to)
Expand All @@ -41,7 +42,7 @@ class PolyfillsResource extends ResourceInterface {

const newHtml = body.replace('<head>', `
<head>
<script src="/${nodeModuleRoot}/${filename}"></script>
<script src="/node_modules/${polyfillPackageName}/${filename}"></script>
`);

resolve(newHtml);
Expand Down

0 comments on commit 9f16979

Please sign in to comment.