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

Bundle.getEntryAssets() ignores CSS files #9745

Open
chky-nmnsoftware opened this issue May 28, 2024 · 0 comments
Open

Bundle.getEntryAssets() ignores CSS files #9745

chky-nmnsoftware opened this issue May 28, 2024 · 0 comments

Comments

@chky-nmnsoftware
Copy link

🐛 bug report

The Parcel API Bundle.getEntryAssets() seems to ignore (or fail to create the appropriate properties) CSS files. This is present in the newer versions of the bundler.

🎛 Configuration (.babelrc, package.json, cli command)

package.json

{
  "name": "my-project",
  "version": "1.0.0",
  "source": "./src/index.html",
  "scripts": {
    "build": "npm run clearCache && node parcel-build.mjs",
    "clearCache": "rm -rf ./.parcel-cache"
  },
  "dependencies": {
    "core": "file:../core"
  },
  "devDependencies": {
    "parcel": "^2.8.3",
    "punycode": "^1.4.1",
    "querystring-es3": "^0.2.1",
    "url": "^0.11.1"
  }
}

parcel-build.mjs

import { Parcel } from '@parcel/core';
import path from 'path';
import { fileURLToPath } from 'url';
import { writeFile } from 'fs/promises';
import chalk from "chalk";

// Required to convert the current module URL to a path
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

async function buildAndRetrieveHashes() {
    // Define the entry file or directory
    const entryFile = path.join(__dirname, 'src/index.html');
    const distDir = path.join(__dirname, 'build')

    // Initialize a new Parcel bundler
    const bundler = new Parcel({
        entries: entryFile,
        defaultConfig: '@parcel/config-default',
        mode: 'production', // 'production' or 'development'
        targets: {
            default: {
                distDir: distDir,
                publicUrl: "."
            }
        },
        additionalReporters: [{packageName: '@parcel/reporter-cli', resolveFrom: __filename}]
    });

    try {
        // Run the bundler to build the project
        const { bundleGraph } = await bundler.run();

        // Extract the mapping of files to hashes
        const fileObject = {}
        bundleGraph.getBundles().forEach(bundle => {
            bundle.getEntryAssets().forEach(asset => {
                fileObject[path.basename(asset.filePath)] = path.basename(bundle.filePath);
            });
        });

        // Save the mapping to a JSON file inside the dist directory
        const mappingsFilePath = path.join(distDir, 'mappings.json');
        await writeFile(mappingsFilePath, JSON.stringify(fileObject, null, 2));

        console.log(chalk.green.bold("\n✨ File to hash mapping saved to ") + chalk.dim("build/") + chalk.white.bold(path.basename(mappingsFilePath)) + chalk.green.bold("."));

    } catch (error) {
        console.error('Build failed:', error);
    }
}

buildAndRetrieveHashes();

🤔 Expected Behavior

The mappings.json file should look like this:

{
  "index.html": "index.html",
  "index.ts": "index.0c99cf22.js",
  "DevTools.ts": "DevTools.17cc9604.js",
  "style.css": "index.e7b14b00.css",
  "loading.svg": "loading.3bdf2b49.svg",
  "sad.svg": "sad.b99a0621.svg",
  "runtime-2a12c635e12d1ac1.js": "index.runtime.9cdeac98.js"
}

😯 Current Behavior

The mappings.json file looks like this:

{
  "index.html": "index.html",
  "index.ts": "index.3da6da8c.js",
  "DevTools.ts": "DevTools.bfcd76cf.js",
  "loading.svg": "loading.3bdf2b49.svg",
  "sad.svg": "sad.b99a0621.svg",
  "runtime-86f55f578273a3de.js": "index.runtime.7bfb05a9.js"
}

💁 Possible Solution

N/A

🔦 Context

We use the Parcel API bundler to compile the project and make use of the getBundles() and getEntryAssets() functions in order to map the relations between certain files to their bundled variants. The mappings.json file is then used to retrieve those files and create a custom HTML file to our business' needs.

💻 Code Sample

Here is the main TS file (index.ts) that is included in the HTML and where the CSS gets imported:

import {Loader, LoaderConfig} from "core/src/Loader"
import {Game} from "./Game"

import "core/src/assets/style.css"
import "core/src/assets/dev.css"

import manifest from "./manifest"

import main from "./configs/placements/placement.main"
import desktop from "./configs/placements/placement.desktop"
import mobile from "./configs/placements/placement.mobile"
import vertical from "./configs/placements/placement.vertical"

import languages from "./configs/languages/main"

const config: LoaderConfig = {
    placements: {
        main,
        desktop,
        mobile,
        vertical
    },
    languages
}

new Loader(manifest, config).init((...params) => new Game(...params))

//@ts-ignore
if (module.hot) {module.hot.accept(function () {location.reload()})}

And here is the HTML file (index.html):

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <title>My Game</title>
</head>
<body class="loading">
<script src="./index.ts" type="module"></script>
</body>
</html>

Interestingly enough, everything gets bundled correctly, it is just that the getEntryAssets() function does not return any assets when bundling the CSS file. It is also important to note that when I used console.log() to inspect, when printing the bundle.filePath, everything is outputted, but when printing the bundle.getMainEntry() or bundle.getEntryAssets(), it returns undefined ([] for getEntryAssets()) for the style.css.

🌍 Your Environment

This seems to happen on the newer version of the bundler. When looking at some games that we installed packages at an older date (@parcel/bundler-default version 2.10.3) it works just fine, meanwhile in the current version when running npm i (@parcel/bundler-default version 2.12.0) this issue exists.

Software Version(s)
Parcel 2.8.3
Node 18.16.0
npm/Yarn 9.5.1
Operating System Kubuntu 22.04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant