Skip to content

Commit

Permalink
bundler
Browse files Browse the repository at this point in the history
  • Loading branch information
asika32764 committed Jun 18, 2024
1 parent 7cecc56 commit 701c64b
Showing 1 changed file with 48 additions and 12 deletions.
60 changes: 48 additions & 12 deletions assets/core/src/asset-bundler.mjs
Original file line number Diff line number Diff line change
@@ -1,22 +1,44 @@
import { webpackBundle } from '@windwalker-io/fusion';
import fs from 'fs';
import { globSync } from 'glob';
import path from 'path';
import { findModules } from './asset-sync.mjs';

export async function bundleJS(source = 'src/Module', dest = 'www/assets/js/', options = {}) {
const mainFile = `./resources/assets/src/front/main.ts`;
/**
*
* @param {string} mainFile
* @param {string|string[]} source
* @param {string} dest
* @param {any} options
* @returns {Promise<any>}
*/
export async function bundleJS(
mainFile = `./resources/assets/src/app.ts`,
source = 'src/Module/**/*.ts',
dest = 'www/assets/js/app/app.js',
options = {}
) {
const workingDir = process.cwd();

if (typeof source === 'string') {
source = [source];
}

const files = findFilesFromGlobArray([
...findModules('**/assets/*.ts'),
`${source}/**/*.ts`,
...source,
]);

let listJS = "{\n";

for (const file of files) {
if (file.fullpath.endsWith('.d.ts')) {
continue;
}

let key = file.relativePath.replace(/assets$/, '').toLowerCase();
key = key.substring(0, key.lastIndexOf('.'));
listJS += `'${key}': () => import('./${file.fullpath}'),\n`;
listJS += `'${key}': () => import('${file.fullpath}'),\n`;
}

listJS += "}";
Expand All @@ -29,23 +51,35 @@ loader.register(${listJS});
export default loader;
`;

const base64 = Buffer.from(ts).toString('base64');
const dataUri = `data:text/javascript;base64,${base64}`;
// const base64 = Buffer.from(ts).toString('base64');
// const dataUri = `data:text/javascript;base64,${base64}`;
const tmpDir = workingDir + '/tmp/fusion';
fs.mkdirSync(tmpDir, { recursive: true });

return webpackBundle(
'',
`${dest}/app.js`,
const tmpFile = tmpDir + '/app.js';
fs.writeFileSync(tmpFile, ts);

const r = await webpackBundle(
tmpFile,
dest,
(config) => {
config.devtool = false;
config.entry = dataUri;
config.output.uniqueName = 'app';
// config.entry = dataUri;
// config.output.uniqueName = 'app';
config.output.libraryTarget = 'module';
config.experiments.outputModule = true;
config.resolve.modules.push(path.resolve('./'));
config.context = path.resolve('./');
config.resolve.alias = {
'@main': path.resolve(mainFile)
'@main': path.resolve(mainFile),
'@app': path.resolve(mainFile),
};
}
);

// fs.unlinkSync(tmpFile);

return r;
}

function findFilesFromGlobArray(sources) {
Expand All @@ -70,6 +104,8 @@ function findFiles(src) {
const path = src.substring(0, i);

return globSync(src).map((file) => {
file = file.replace(/\\/g, '/');

return {
fullpath: file,
relativePath: file.substring(path.length)
Expand Down

0 comments on commit 701c64b

Please sign in to comment.