piral-cli-vite
Version:
Provides debug and build capabilities for pilets and Piral instances using Vite.
99 lines • 3.56 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.create = void 0;
const cheerio_1 = require("cheerio");
const path_1 = require("path");
const fs_1 = require("fs");
const common_1 = require("./common");
const bundler_run_1 = require("./bundler-run");
function isLocal(path) {
if (path) {
if (path.startsWith(':')) {
return false;
}
else if (path.startsWith('http:')) {
return false;
}
else if (path.startsWith('https:')) {
return false;
}
else if (path.startsWith('data:')) {
return false;
}
return true;
}
return false;
}
function transformIndexHtml(html) {
const rx = /<script\s+.*<\/script>/gm;
const replacements = [];
while (true) {
const match = rx.exec(html);
if (!match) {
break;
}
const text = match[0];
const templateContent = (0, cheerio_1.load)(text, null, false);
templateContent('script[src]')
.filter((_, e) => isLocal(e.attribs.src))
.each((_, e) => {
if (!e.attribs.type) {
e.attribs.type = 'module';
replacements.push([text, templateContent.html()]);
}
});
}
for (const [original, replacement] of replacements) {
html = html.replace(original, replacement);
}
return html;
}
function getConfigFile(root) {
const fileNames = ['vite.config.ts', 'vite.config.js', 'vite.config.mts', 'vite.config.mjs'];
const files = (0, fs_1.readdirSync)(root);
for (const name of fileNames) {
if (files.includes(name)) {
return (0, path_1.resolve)(root, name);
}
}
return undefined;
}
const handler = {
create(options) {
const rootDir = (0, path_1.dirname)(options.entryFiles);
const newPlugins = [];
const config = (0, common_1.createCommonConfig)(rootDir, options.outDir, options.emulator, options.sourceMaps, options.minify, {
DEBUG_PIRAL: process.env.DEBUG_PIRAL || (process.env.DEBUG_PIRAL = ''),
DEBUG_PILET: process.env.DEBUG_PILET || (process.env.DEBUG_PILET = ''),
SHARED_DEPENDENCIES: JSON.stringify(options.externals.join(',')),
});
if (options.hmr) {
newPlugins.push({
name: 'hmr-plugin',
generateBundle(_, bundle) {
if (bundle) {
Object.keys(bundle).forEach((file) => {
const asset = bundle[file];
if (asset.type === 'chunk' && asset.isEntry) {
asset.code = `(() => new WebSocket(location.origin.replace('http', 'ws')+"/$events").onmessage = () => location.reload())();${asset.code}`;
}
});
}
},
});
}
const configFile = getConfigFile(options.root);
const indexHtml = (0, path_1.resolve)(rootDir, 'index.html');
const content = (0, fs_1.readFileSync)(indexHtml, 'utf8');
(0, fs_1.writeFileSync)(indexHtml, transformIndexHtml(content), 'utf8');
return (0, bundler_run_1.runVite)({
...config,
configFile,
plugins: [...config.plugins, ...newPlugins],
debug: options.watch,
outFile: options.outFile,
});
},
};
exports.create = handler.create;
//# sourceMappingURL=piral.js.map