Skip to content

Commit e1abd7c

Browse files
fix: make a workaround for config relative imports issues (#170)
* refactor: use node's `vm` module instead of `eval` * fix: set the vm's `__dirname` global to the path of the config file This is a workaround for errors from relative imports inside the config by using the `__dirname` global in imports
1 parent 71cbd39 commit e1abd7c

File tree

1 file changed

+15
-10
lines changed

1 file changed

+15
-10
lines changed

src/cli/core/GeneratedFileWriter.ts

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
/* eslint-disable @typescript-eslint/restrict-template-expressions */
22

33
import {promises as fs} from 'fs';
4+
import vm from 'vm';
45
import path from 'path';
56
import colors from 'colors';
67
import {ClassnamesGenerator} from './ClassnamesGenerator';
7-
import {TTailwindCSSConfig} from '../types/config';
88
import {TailwindConfigParser} from './TailwindConfigParser';
99
import {FileContentGenerator} from './FileContentGenerator';
10+
import {TTailwindCSSConfig as TConfig} from '../types/config';
1011

1112
type TCliOptions = {
1213
configFilename: string | void;
@@ -70,22 +71,26 @@ export class GeneratedFileWriter {
7071

7172
private generateFileContent = (): string => {
7273
// Evaluate the config as a JS object
73-
const configEval = eval(
74-
this._configFileData.replace(/(['"])?plugins(['"])? *: *\[(.*|\n)*?],?/g, ''),
75-
) as TTailwindCSSConfig;
74+
const evaluatedConfig = <TConfig>vm.runInNewContext(this._configFileData, {
75+
__dirname: path.dirname(path.resolve(`./${this._configFilename}`)),
76+
module: {},
77+
require,
78+
});
7679

77-
// Parse the config with the config scanner
78-
const scanner = new TailwindConfigParser(configEval, {
80+
// Parse the config with the config parser class
81+
const configParser = new TailwindConfigParser(evaluatedConfig, {
7982
pluginTypography: this._configFileData.includes('@tailwindcss/typography'),
8083
pluginCustomForms: this._configFileData.includes('@tailwindcss/custom-forms'),
8184
});
8285

8386
// Generate all classnames from the config
84-
const generatedClassnames = new ClassnamesGenerator(scanner).generate();
87+
const generatedClassnames = new ClassnamesGenerator(configParser).generate();
8588

86-
// Create the file content from the generated classes
87-
const contentGenerator = new FileContentGenerator(generatedClassnames, scanner.getPrefix());
88-
const fileContentTemplate = contentGenerator.generateFileContent();
89+
// Create the file content from the generated classnames
90+
const fileContentTemplate = new FileContentGenerator(
91+
generatedClassnames,
92+
configParser.getPrefix(),
93+
).generateFileContent();
8994

9095
// Resolve the custom classes import path relative to the output file
9196
let customClassesImportPath: string | null = null;

0 commit comments

Comments
 (0)