Skip to content

Support tsx with CommonJS config files #3304

@zachleat

Description

@zachleat

https://tsx.is/node/cjs#programmatic-api

Doesn’t work:

const { renderToString } = require('react-dom/server');

require('tsx/cjs');

module.exports = function(eleventyConfig) {
	eleventyConfig.addTemplateFormats("11ty.tsx");
	eleventyConfig.addExtension("11ty.tsx", {
		key: "11ty.js",
		compile: function() {
			return async function(data) {
				let content = await this.defaultRenderer(data);
				return renderToString(content);
			};
		}
	});
};

Results in this:

[11ty] Problem writing Eleventy templates: (more in DEBUG output)
[11ty] Unknown file extension ".tsx" for /Users/zachleat/Temp/eleventy-tsx-demo/test.11ty.tsx (via TypeError)
[11ty] 
[11ty] Original error stack trace: TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".tsx" for /Users/zachleat/Temp/eleventy-tsx-demo/test.11ty.tsx
[11ty]     at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:160:9)
[11ty]     at defaultGetFormat (node:internal/modules/esm/get_format:203:36)
[11ty]     at defaultLoad (node:internal/modules/esm/load:143:22)
[11ty]     at async ModuleLoader.load (node:internal/modules/esm/loader:403:7)
[11ty]     at async ModuleLoader.moduleProvider (node:internal/modules/esm/loader:285:45)
[11ty]     at async link (node:internal/modules/esm/module_job:78:21)
[11ty] Wrote 0 files in 0.01 seconds (v3.0.0-alpha.11)

Reason: Eleventy uses import under the hood to dynamically load CommonJS files.

Works:

The workaround here is to use ESM for your config file/project.

import { renderToString } from 'react-dom/server';

import 'tsx/esm';

export default function(eleventyConfig) {
	eleventyConfig.addTemplateFormats("11ty.tsx,11ty.ts,11ty.jsx");
	eleventyConfig.addExtension(["11ty.jsx", "11ty.ts", "11ty.tsx"], {
		key: "11ty.js",
		compile: function() {
			return async function(data) {
				let content = await this.defaultRenderer(data);
				return renderToString(content);
			};
		}
	});
};

Worth noting that this one is fixable (fork for require in Eleventy when dealing with CommonJS files internally) but maybe not worth it!

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions