Skip to content

Commit

Permalink
fix(module): improve templates…
Browse files Browse the repository at this point in the history
  • Loading branch information
ThornWalli committed Dec 14, 2023
1 parent 94ed209 commit 87206fc
Show file tree
Hide file tree
Showing 4 changed files with 96 additions and 51 deletions.
1 change: 0 additions & 1 deletion .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,5 @@ publish
sw.js
.output

src/runtime/tmpl/**/*
docs/.vitepress/dist
docs/.vitepress/cache
59 changes: 32 additions & 27 deletions src/module.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ import { getSupportedBrowserDetector } from './utils/browser.js';
import { registerAppEntry as registerAppEntryWebpack } from './hookFunctions/webpack.js';
import { registerAppEntry as registerAppEntryVite } from './hookFunctions/vite.js';

import pluginTemplate from './tmpl/plugin.tmpl.js';
import entryTemplate from './tmpl/entry.tmpl.js';

const resolver = createResolver(import.meta.url);

export default defineNuxtModule({
Expand Down Expand Up @@ -55,14 +58,14 @@ export default defineNuxtModule({
nuxt.hook(
'webpack:config',
registerAppEntryWebpack(
resolve(nuxt.options.buildDir, MODULE_NAME, 'entry.mjs')
resolve(nuxt.options.buildDir, MODULE_NAME, 'entry.js')
)
);
} else {
nuxt.hook(
'vite:extend',
registerAppEntryVite(
resolve(nuxt.options.buildDir, MODULE_NAME, 'entry.mjs')
resolve(nuxt.options.buildDir, MODULE_NAME, 'entry.js')
)
);
}
Expand Down Expand Up @@ -111,36 +114,38 @@ async function addBuildTemplates(nuxt, options) {

['client', 'server'].forEach(mode => {
addPluginTemplate({
src: resolver.resolve('runtime/tmpl', 'plugin.mjs'),
fileName: MODULE_NAME + `/plugin.${mode}.js`,
getContents: () => {
return pluginTemplate({
mode,
densities: options.densities,
targetFormats: options.targetFormats,
crossorigin: getCrossorigin(options.crossorigin),
supportedBrowserDetector,
loader: options.loader
});
},
filename: MODULE_NAME + `/plugin.${mode}.js`,
write: true,
mode,
options: {
mode,
densities: options.densities,
targetFormats: options.targetFormats,
crossorigin: getCrossorigin(options.crossorigin),
supportedBrowserDetector,
loader: options.loader
}
mode
});
});

addTemplate({
src: resolver.resolve('runtime/tmpl', 'entry.mjs'),
fileName: MODULE_NAME + '/entry.mjs',
write: true,
options: {
webpack: isWebpackBuild(nuxt),
performanceCheck: true,
isDev: !options.debug && process.env.NODE_ENV === 'development',
entry: join(nuxt.options.appDir, 'entry'),
runOptions: options.runOptions,
ssr: nuxt.options.ssr,
ignorePerformance: !options.detection.performance,
performanceMetrics: JSON.stringify(options.performanceMetrics || {}),
supportedBrowserDetector
}
filename: MODULE_NAME + '/entry.js',
getContents: () => {
return entryTemplate({
webpack: isWebpackBuild(nuxt),
performanceCheck: true,
isDev: !options.debug && process.env.NODE_ENV === 'development',
entry: join(nuxt.options.appDir, 'entry'),
runOptions: options.runOptions,
ssr: nuxt.options.ssr,
ignorePerformance: !options.detection.performance,
performanceMetrics: JSON.stringify(options.performanceMetrics || {}),
supportedBrowserDetector
});
},
write: true
});
}

Expand Down
50 changes: 39 additions & 11 deletions src/runtime/tmpl/entry.mjs → src/tmpl/entry.tmpl.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,23 @@
import { <% if (options.performanceCheck) { %>run, <% } %>hasSufficientPerformance, setup } from '#speedkit/utils/performance';
export default options => {
debugger;

Check warning on line 2 in src/tmpl/entry.tmpl.js

View workflow job for this annotation

GitHub Actions / Install (ubuntu-latest, 20)

Unexpected 'debugger' statement
let code = `import { ${
options.performanceCheck ? `run, ` : ``
}hasSufficientPerformance, setup } from '#speedkit/utils/performance';
import { triggerRunCallback, observeSpeedkitButton, setupSpeedkitLayer, updateSpeedkitLayerMessage, initReducedView } from '#speedkit/utils/entry';
import Deferred from '#speedkit/classes/Deferred.js';
import { isSupportedBrowser } from '#speedkit/utils/browser';
<% if (options.webpack) { %>
`;

if (options.webpack) {
code += `
// webpack
(async () => {
return await client().then(() => getEntry());
})()
<% } else {%>
`;
} else {
code += `
// vite
export default entryWrapper();
Expand All @@ -21,9 +30,12 @@ function entryWrapper(){
}
};
<%} %>
`;
}

code += `
function getEntry(){
return import('<%= options.entry %>.js').then(module => module.default);
return import('${options.entry}.js').then(module => module.default);
}
function client () {
Expand All @@ -43,9 +55,19 @@ function client () {
try {
<% if (options.performanceCheck) { %>if (!force) {
await run(<%= options.runOptions ? JSON.stringify(options.runOptions) : '' %>);
}<% } %>
`;

if (options.performanceCheck) {
code += `
if (!force) {
await run(${
options.runOptions ? JSON.stringify(options.runOptions) : ''
});
}
`;
}

code += `
initialized = true;
Expand All @@ -66,7 +88,9 @@ function client () {
return null;
};
const supportedBrowser = isSupportedBrowser(<%= options.supportedBrowserDetector %>);
const supportedBrowser = isSupportedBrowser(${
options.supportedBrowserDetector
});
window.addEventListener('load', function () {
if (!document.getElementById('nuxt-speedkit-layer')) {
Expand All @@ -76,9 +100,9 @@ function client () {
observeSpeedkitButton('nuxt-speedkit-button-init-reduced-view', initReducedView);
observeSpeedkitButton('nuxt-speedkit-button-init-app', () => initApp(true));
setup(<%= options.performanceMetrics %>);
setup(${options.performanceMetrics});
if(('__NUXT_SPEEDKIT_AUTO_INIT__' in window && window.__NUXT_SPEEDKIT_AUTO_INIT__) || ((<%= !options.ignorePerformance %> && hasSufficientPerformance()) && supportedBrowser)) {
if(('__NUXT_SPEEDKIT_AUTO_INIT__' in window && window.__NUXT_SPEEDKIT_AUTO_INIT__) || ((${!options.ignorePerformance} && hasSufficientPerformance()) && supportedBrowser)) {
initApp();
} else {
setupSpeedkitLayer(layerEl, supportedBrowser)
Expand All @@ -90,3 +114,7 @@ function client () {
return deferred.promise;
}
`;

return code;
};
37 changes: 25 additions & 12 deletions src/runtime/tmpl/plugin.mjs → src/tmpl/plugin.tmpl.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import vFont from '#speedkit/directives/vFont';
export default options => {
let code = `import vFont from '#speedkit/directives/vFont';
import { isSupportedBrowser } from '#speedkit/utils/browser';
import FontList from '#speedkit/classes/FontList';
import hydrate from '#speedkit/hydrate';
Expand All @@ -18,10 +19,14 @@ export default defineNuxtPlugin({
getImageSize,
hydrate,
getFont: fontList.getFont.bind(fontList),
crossorigin: <%= options.crossorigin ? `'${options.crossorigin}'` : null %>,
isBrowserSupported: () => isSupportedBrowser(<%= options.supportedBrowserDetector %>),
targetFormats: <%= JSON.stringify(options.targetFormats) %>,
densities: <%= JSON.stringify(options.densities) %>
crossorigin: ${
options.crossorigin ? "'" + options.crossorigin + "'" : null
},
isBrowserSupported: () => isSupportedBrowser(${
options.supportedBrowserDetector
}),
targetFormats: ${JSON.stringify(options.targetFormats)},
densities: ${JSON.stringify(options.densities)}
});
},
Expand All @@ -36,15 +41,17 @@ export default defineNuxtPlugin({
async function getImageSize (src) {
<% if (options.mode === 'client') { %>
const { width, height } = await new Promise((resolve) => {
`;

if (options.mode === 'client') {
code += ` const { width, height } = await new Promise((resolve) => {
const img = new global.Image();
img.onload = () => resolve({width: img.naturalWidth, height: img.naturalHeight});
img.src = src;
});
return {width, height};
<% } else { %>
return {width, height};`;
} else {
code += `
const isNitroPrerender = 'x-nitro-prerender' in useRequestHeaders()
try {
Expand All @@ -64,9 +71,15 @@ async function getImageSize (src) {
const { width, height } = await imageMeta(data);
return { width, height };
} catch (error) {
console.error(`getImageSize: ` + src, error);
console.error('getImageSize: ' + src, error);
return { width: 0, height: 0 };
}
`;
}

code += `
}
`;

<% } %>
return code;
};

0 comments on commit 87206fc

Please sign in to comment.