Reputation: 139
I am developing a TailwindCSS plugin and need to create a helper function that serves the configuration object, including those which come from the plugin, from the tailwind.config.js file. There are helper functions such as config() or theme() to do this; however, this helper function is outside the program's scope and should be able to serve the config object to the global scope.
About documentation:
Tailwind documentation points to resolveConfig helper function in these situations
To make this easy, Tailwind provides a resolveConfig helper you can use to generate a fully merged version of your configuration object
However, this function gives me the default Tailwind configuration object, which does not contain any custom keys—keys that are provided by the plugin.
This of course, doesn't work:
import resolve from "tailwindcss/resolveConfig.js"
import config from "path/to/config.js" with { type: "json" }
console.log(resolve(config)) // logs the default tailwind config file
Actual code:
import resolveConfig from "tailwindcss/resolveConfig.js"
import * as configFile from "../../tailwind.config.js"
import resolveObject from "./resolve-object.js"
function getConfigFile(path?: string) {
const config = resolveConfig(configFile)
if (!path) return config
return resolveObject({ object: config, path: path })
}
export { getConfigFile }
ResolveObject
getConfigFile()
does not work either, therefore this is not related and you may skip it.
type ResolveObjectProps = {
object: { [key: string]: any },
path: string
}
function resolveObject({ object, path }: ResolveObjectProps) {
if (!path.includes("."))
return object[path]
let segments = path.split(".")
const segment = segments.shift()
if (typeof segment !== "undefined") {
return resolveObject({ object: object[segment], path: segments.join(".") })
}
return object
}
export default resolveObject
export type { ResolveObjectProps }
Non-Technical: I can use fs to do this, or an async function with dynamic import, or with billion other ways, but I am not sure if this a user error or tailwind really cleanes the default exported object before returning it or maybe resolveConfig just returns the default tailwind configuration object, if this is the situation then what is the purpose of resolveConfig's first parameter?
Upvotes: 1
Views: 388
Reputation: 139
I guess resolveConfig
is not meant to be used to get a custom configuration object. See the solution below
import defaultConfig from "tailwindcss/defaultConfig.js"
import resolveConfig from "tailwindcss/resolveConfig.js"
import configFileObject from "../../tailwind.config.mjs"
import resolveObject from "./resolve-object.js"
import { deepmerge } from "deepmerge-ts"
function getConfig(path?: string) {
const config = deepmerge(
resolveConfig(defaultConfig),
configFileObject
)
if (!path) return config
return resolveObject({ object: config, path: path })
}
export { getConfigFile }
Upvotes: 0