Use shell heredoc syntax as a workaround when write_file fails on complex TypeScript/JSX/code files with encoding or escaping issues
复制下面这句话,粘贴给 Claude Code、Codex、Cursor 等 AI 编程工具,它会读取安装说明并在你确认后完成安装。
请阅读 https://ai.atlankj.com/install/asset/gh-heredoc-file-write-6bccc2db32ab ,按照其中的说明把「heredoc-file-write」安装到你(当前 AI 工具)中。执行前先告诉我将运行的命令和写入的位置,等我确认。
查看 AI 将读取的安装说明正在读取 GitHub 原文…
内容来自 GitHub 原始文件,由原作者维护。在 GitHub 查看
Use this pattern when:
write_file repeatedly fails with "unknown error" or similar messagesSwitch from write_file to run_shell using heredoc syntax with cat. The heredoc approach handles special characters, quotes, and complex content more reliably.
When write_file fails repeatedly on the same file:
Execute shell command with heredoc:
cat > /path/to/file.tsx << 'EOF'
// Your file content here
import React from 'react';
const Component = () => {
return <div>Hello</div>;
};
export default Component;
EOF
Use quoted delimiter ('EOF' not EOF) to prevent variable expansion:
'EOF' = literal content (recommended for code files)EOF = allows variable expansion (use only if needed)Match delimiters exactly: Opening and closing EOF must be on their own lines with no leading/trailing whitespace
No escaping needed: Content between delimiters is taken literally when using quoted delimiter
After executing the heredoc command:
ls -la /path/to/file.tsxcat /path/to/file.tsx or head -20 /path/to/file.tsxcat > src/components/Button.tsx << 'EOF'
import React from 'react';
interface ButtonProps {
label: string;
onClick: () => void;
}
export const Button: React.FC<ButtonProps> = ({ label, onClick }) => {
return (
<button onClick={onClick} className="btn-primary">
{label}
</button>
);
};
EOF
cat > tsconfig.json << 'EOF'
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"strict": true,
"esModuleInterop": true
},
"include": ["src/**/*"]
}
EOF
cat > deploy.sh << 'EOF'
#!/bin/bash
set -e
echo "Deploying..."
if [ "$ENV" = "production" ]; then
echo "Production deployment"
fi
EOF
write_file for dynamic content generationProblem: File not created at expected path
pwdProblem: Content appears corrupted
'EOF') and closing delimiter has no trailing whitespaceProblem: Permission denied