연구 설문조사: Blockly 사용 경험을 알려주세요
설문조사 시작
코드 생성
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
코드 생성은 작업공간의 블록을 실행 가능한 코드 문자열로 변환하는 프로세스입니다.
코드 생성은 매우 중요합니다. 블록이 산술식 평가, 미로에서 캐릭터 이동, 온라인 상점 구성과 같은 작업을 실제로 실행할 수 있도록 하기 때문입니다.
블록을 직접 '실행'할 수는 없습니다. 대신 코드 문자열을 생성한 다음 실행합니다.
언어 코드 생성기
코드를 생성하려면 생성할 텍스트 기반 언어를 선택해야 합니다. 각 언어에는 자체 코드 생성기가 있기 때문입니다.
언어 코드 생성기 (일반적으로 코드 생성기라고 함)는 특정 언어에만 국한되지 않고 개별 블록에만 국한되지 않는 코드 생성 규칙을 처리하는 클래스입니다. 예를 들어 주석 형식 지정, 문장 들여쓰기, 문자열 따옴표 넣기 등을 처리합니다.
Blockly는 5가지 기본 제공 코드 생성기를 제공합니다.
- JavaScript ES5
- Python 3
- Lua 5.1
- Dart 2
- PHP 7
이 목록에 코드를 생성하려는 언어가 포함되어 있지 않으면 맞춤 언어 코드 생성기를 만들 수 있습니다. 간단한 예는 JSON 언어 코드 생성기를 만드는 맞춤 생성기 빌드 Codelab을 참고하세요. 더 복잡한 예는 JavaScript 코드 생성기를 참고하세요. 또한 사용하려는 모든 내장 블록에 대해 블록 코드 생성기를 작성해야 합니다.
블록 코드 생성기
각 블록은 자체 코드를 생성합니다. 블록을 만들 때는 지원하려는 언어별로 별도의 블록 코드 생성기를 작성해야 합니다.
블록 코드 생성기는 해당 블록의 코드를 문자열로 반환하는 함수입니다. 예를 들어 두 숫자를 비교하는 블록은 'a < b'
형식의 문자열을 반환하고 if 문을 나타내는 블록은 'if (...) {\n...\n};\n'
형식의 문자열을 반환합니다.
import {javascriptGenerator} from 'blockly/javascript';
import {pythonGenerator} from 'blockly/python';
// Write block-code generators for JavaScript and Python.
javascriptGenerator.forBlock['my_custom_block'] = function(block, generator) { /* ... */ };
pythonGenerator.forBlock['my_custom_block'] = function(block, generator) { /* ... */ };
블록 코드 생성기는 언어 코드 생성기에서 호출합니다.
자세한 내용은 블록 코드 생성기를 참고하세요.
코드 생성 및 실행
애플리케이션은 언제든지 코드를 생성할 수 있습니다. 예를 들어 최종 사용자가 버튼을 클릭하거나 사용자가 변경할 때마다 코드를 생성할 수 있습니다.
코드를 생성한 후에는 코드를 실행하는 방법을 알아야 합니다.
실행 방법을 결정하는 것은 애플리케이션에 따라 다르며 Blockly의 범위를 벗어납니다.
자세한 내용은 코드 생성 및 실행을 참고하세요.
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다.
최종 업데이트: 2025-07-25(UTC)
[null,null,["최종 업데이트: 2025-07-25(UTC)"],[[["\u003cp\u003eCode generation transforms Blockly blocks into executable code strings in various programming languages like JavaScript, Python, Lua, Dart, and PHP.\u003c/p\u003e\n"],["\u003cp\u003eBlockly offers built-in code generators for these languages, accessible through modules, Unpkg, or local scripts, along with the option to create custom generators.\u003c/p\u003e\n"],["\u003cp\u003eGenerating code involves defining how individual blocks translate to code in each target language, including handling fields, inner blocks, and code concatenation.\u003c/p\u003e\n"],["\u003cp\u003eCode generation can be triggered on demand or continuously as the user interacts with the blocks, allowing for dynamic updates and code execution.\u003c/p\u003e\n"],["\u003cp\u003eDevelopers can add preamble or postscript code to the generated output for including external definitions or initiating specific behaviors.\u003c/p\u003e\n"]]],["Code generation transforms visual blocks into executable code strings. A code generator handles language-specific formatting. Blockly offers built-in generators for JavaScript, Python, Lua, Dart, and PHP, accessible via modules, Unpkg, or local scripts. Custom generators are also supported. Each block's code generation rules must be defined per language. Generation occurs on demand or continuously via event listeners. Optional preamble/postscript code can be added. Execution of generated code is application-specific, and for JavaScript, JSInterpreter is suggested.\n"],null,["# Code generation is the process of turning the blocks on a workspace into a\nstring of code that can be executed.\n\nCode generation is extremely important, because it is what allows your blocks to\nactually *do* things, like evaluate arithmetic expressions, move a character\nthrough a maze, or configure an online shop!\n\nYou can't \"run\" blocks directly. Instead you generate code strings, and then\nexecute those.\n\nLanguage code generators\n------------------------\n\nTo generate code, you have to pick what text-based language you want to\ngenerate. This is because each language has its own code generator.\n\nA **language code generator** (commonly called a **code generator**) is a class\nthat handles the rules for generating code that are specific to a given\nlanguage, but not specific to an individual block. For example, it handles\nthings like formatting comments, indenting statements, and quoting strings.\n\nBlockly provides 5 built-in code generators:\n\n- JavaScript ES5\n- Python 3\n- Lua 5.1\n- Dart 2\n- PHP 7\n\nIf this list doesn't include the language you want to generate code for, you can\ncreate a custom language code generator. For a simple example, see the [Build a\ncustom generator](https://blocklycodelabs.dev/codelabs/custom-generator/index.html?index=..%2F..index#0) codelab, which creates a JSON language\ncode generator. For a more complex example, see the [JavaScript code\ngenerator](https://github.com/google/blockly/blob/master/generators/javascript/javascript_generator.ts). Note that you also need to write block-code\ngenerators for any built-in blocks that you want to use.\n\nBlock-code generators\n---------------------\n\nEach block is responsible for generating its own code. When you create a block,\nyou need to write a separate block-code generator for each language you want to\nsupport.\n\nA **block-code generator** is a function that returns the code for that block as\na string. For example, a block that compares two numbers returns a string of the\nform `'a \u003c b'` and a block that represents an if statement returns a string of\nthe form `'if (...) {\\n...\\n};\\n'`. \n\n import {javascriptGenerator} from 'blockly/javascript';\n import {pythonGenerator} from 'blockly/python';\n\n // Write block-code generators for JavaScript and Python.\n javascriptGenerator.forBlock['my_custom_block'] = function(block, generator) { /* ... */ };\n pythonGenerator.forBlock['my_custom_block'] = function(block, generator) { /* ... */ };\n\nBlock-code generators are called by language code generators.\n\nFor more information, see [Block-code\ngenerators](/blockly/guides/create-custom-blocks/code-generation/block-code).\n\nGenerate and run code\n---------------------\n\nYour application can generate code at any time. For example, it might generate\ncode when the end-user clicks a button or every time the user makes a change.\n\nAfter you've generated the code, you need to figure out how to execute it.\nDeciding how to execute it is very application-specific, and outside the scope\nof Blockly.\n\nFor more information, see [Generate and run\ncode](/blockly/guides/app-integration/run-code)."]]