Search code examples
astrojs

Read Astro Config Values


My astro.config.mjs is as follows:

export default defineConfig({
  compressHTML: false,
  experimental: {
    contentCollectionCache: true,
  },
  build: {
    assets: "_custom"
  },
  integrations: [
  ]
})

During an SSG build is it possible to get a reference to build.assets from astro.config.mjs


Solution

  • One way to do this is using an integration that exposes the Astro config using a virtual module, here is an example using astro-integration-kit

    import type { AstroIntegration } from "astro";
    import { addVirtualImport } from "astro-integration-kit";
    
    export default function myIntegration(): AstroIntegration {
        return {
            name: "my-integration",
            hooks: {
                "astro:config:setup": ({ config, updateConfig }) => {
                    addVirtualImport({
                        name: 'virtual:my-integration/config',
                        content: `export default ${JSON.stringify(config)}`,
                        updateConfig,
                    })
                }
            }
        }
    }
    
    import { defineConfig } from 'astro/config'
    import myintegration from './myintegration';
    
    export default defineConfig({
      integrations: [myintegration()]
    })
    
    import config from 'virtual:my-integration/config';
    
    console.log(config.build.assets)