Printable

Contribute

webpack에 기여하는 사람들은 오픈 소스, 사용자 및 생태계를 사랑합니다. 그리고 가장 중요한 것은 웹을 함께 발전시키는 것입니다. 펀딩의 투명성을 위한 Open Collective 모델으로 컨트리뷰터, 디펜던트 프로젝트, 코어 팀으로부터 지원과 펀딩을 받을 수 있습니다. 기부하려면 아래 버튼을 클릭하세요.

이 투자에 대해서 어떤게 돌아올까요?

Developers

우리가 제공하고자 하는 가장 큰 핵심 기능은 즐거운 개발 경험입니다. 여러분과 같은 개발자는 풍부하고 생생한 문서에 기여할 수도 있고, Pull Request를 등록하여 세부적인 사용 사례를 해결하거나, 여러분이 좋아하는 webpack을 유지하도록 도와줄 수 있습니다.

How Can I Help?

누구나 다음 중 하나를 통해 도움을 줄 수 있습니다.

  • 고용주에게 프로젝트에 webpack을 사용하도록 요청하세요.
  • 이 사이트의 콘텐츠를 작성하고 유지하도록 도와주세요. (writer's guide 참고)
  • 코어 저장소에 기여하세요.
  • open collective의 개인 후원자 또는 기업 스폰서가 되주세요.

Encouraging Employers

고용주에게 webpack을 사용하여 작업 흐름을 개선하도록 요청할 수 있습니다. webpack은 폰트, 이미지 및 이미지 최적화, json을 위한 올인원 도구입니다. webpack이 어떻게 최적화된 방법으로 코드와 애셋을 번들하여 가장 작은 크기의 파일을 만들고, 이를 통해 사이트와 애플리케이션을 더 빠르게 만들 수 있는지 설명해주세요.

Your Contributions

webpack에 기여하는 것은 전용 클럽에 기여하는 것이 아닙니다. 여러분과 같은 개발자는 다운 스트림 프로젝트의 전반적인 건전성에 기여하고 있습니다. 수천 개는 아니더라도 수백 개의 프로젝트가 webpack에 의존하고 있습니다. webpack에 기여하면 모든 사용자에게 더 나은 생태계를 만들 것입니다.

이 섹션의 나머지 부분은 계속 성장하는 우리 커뮤니티의 일원이 되고자 하는 여러분과 같은 개발자를 위한 것입니다.

Executives

CTO, VP 및 오너도 도울 수 있습니다!

Webpack은 코드 번들링을 위한 올인원 도구입니다. 커뮤니티 기반 플러그인과 로더의 도움으로 폰트, 이미지, 데이터 등을 처리 할 수 있습니다. 하나의 도구로 모든 애셋을 처리하는 것은 매우 유용합니다. 움직이는 부품이 많은 기계가 올바르게 작동하는지 확인하는 데 드는 시간을 줄이고 제품을 만드는 데 더 많은 시간을 할애 할 수 있습니다.

Sponsorship

기업은 금전적인 지원 외에도 다음과 같은 방법으로 webpack을 후원할 수 있습니다.

  • 프로젝트에 참여하고 있지 않은 개발자를 지원해주세요.
  • 개선된 CI 및 회귀 테스트를 위해 컴퓨팅 파워에 기여합니다.

webpack 로더, 플러그인 및 기타 유틸리티를 오픈 소싱하여 개발자가 생태계에 기여하도록 장려 할 수도 있습니다. 그리고 위에서 언급했듯이 CI/CD 인프라를 늘리는 데 도움을 주시면 감사하겠습니다.

Anyone Else

우리의 사명을 돕는 데 관심이있는 다른 분(예: 벤처 자본가, 정부 기관, 디지털 대행사 등)이 있다면, 같이 일하기를 원합니다. 최고의 npm 패키지 중 하나인 당사와 협력하여 제품을 개선해보세요! 궁금한 점이 있으면 언제든지 문의해 주세요.

Community

도움이 필요하거나, 궁금한 점이 있거나, 다른 Webpack 기여자들과 소통하고 싶으신가요?

실시간 지원, 토론, 협업을 위해 Discord 서버에 가입하세요.

Pull requests

webpack이 발전함에 따라 webpack 기능 및 변경 사항에 대한 문서가 업데이트되고 있습니다. 자동화된 이슈 생성이 통합되었고 최근 몇 년 동안 효과적인 것으로 입증되었습니다. 어떤 기능이 병합되면 문서 요청 관련 이슈가 저장소에 생성되고 곧 해결될 것으로 예상합니다. 이는 리뷰와 릴리스를 기다리는 기능 및 변경 사항이 있음을 의미합니다. 즉 Pull Request의 작성자가 30일 이상 이를 방치하는 경우 해당 Pull Request를 오래된 것으로 표시 할 수 있습니다. 기능을 완료하는 데 필요한 작업을 인계받을 수도 있습니다. Pull Request 작성자가 자신이 포크한 저장소에 webpack 문서 팀의 쓰기 권한을 부여하면 우리가 브랜치에 직접 커밋하고 작업을 완료합니다. 다른 경우에는 우리 스스로 또는 커뮤니티 멤버에게 위임하여 다시 시작해야 할 수도 있습니다. 이로 인해 Pull Request가 중복될 수 있으며 정리 프로세스에서 닫힐 수 있습니다.

Governance Overview

webpack Project Governance

webpack is an open source project that depends on contributions from the community. Anyone may contribute to the project at any time by submitting code, participating in discussions, making suggestions, or any other contribution they see fit. This document describes how various types of contributors work within the webpack project.

Roles and Responsibilities

Contributors

Contributors are community members who contribute in concrete ways to the project, most often in the form of code and/or documentation. Anyone can become a Contributor, and contributions can take many forms. There is no expectation of commitment to the project, no specific skill requirements, and no selection process.

Contributors have read-only access to source code and so submit changes via pull requests. Contributor pull requests have their contribution reviewed and merged by a TSC member. TSC members and Committers work with Contributors to review their code and prepare it for merging.

As Contributors gain experience and familiarity with the project, their profile within, and commitment to, the community will increase. At some stage, they may find themselves being nominated as either a Website Team Member or Committer by an existing Website Team Member or Committer.

Committers

Committers are community members who have shown that they are committed to the continued development of the project through ongoing engagement with the community. Committers are given push access to the project's GitHub repos and must abide by the project's Contribution Guidelines

To become a Committer:

  • One must have shown a willingness and ability to participate in the project as a team player. Typically, a potential Committer will need to show that they have an understanding of and alignment with the project, its objectives, and its strategy.
  • Committers are expected to be respectful of every community member and to work collaboratively in the spirit of inclusion.

New Committers can be nominated by any existing Committer. Once they have been nominated, there will be a vote by the TSC members.

It is important to recognize that committership is a privilege, not a right. That privilege must be earned and once earned it can be removed by the TSC members by a standard TSC motion. However, under normal circumstances committership exists for as long as the Committer wishes to continue engaging with the project.

A Committer who shows an above-average level of contribution to the project, particularly with respect to its strategic direction and long-term health, may be nominated to become a reviewer, described below.

Reviewers

Reviewers are community members who have contributed a significant amount of time to the project through triaging of issues, fixing bugs, implementing enhancements/features, and are trusted community leaders.

Reviewers may perform all of the duties of Committers, and also:

  • May merge external pull requests for accepted issues upon reviewing and approving the changes.
  • May merge their own pull requests once they have collected the feedback they deem necessary. (No pull request should be merged without at least one Committer/Reviewer/TSC member comment stating they've looked at the code.)

To become a Reviewer:

  • Work in a helpful and collaborative way with the community.
  • Have given good feedback on others' submissions and displayed an overall understanding of the code quality standards for the project.
  • Commit to being a part of the community for the long-term.

A Committer is invited to become a Reviewer by existing Reviewers and TSC members. A nomination will result in discussion and then a decision by the TSC.

Technical Steering Committee

A subset of the collaborators forms the Technical Steering Committee (TSC). The TSC has final authority over this project, including:

  • Technical direction
  • Project governance and process (including this policy)
  • Contribution policy
  • GitHub repository hosting
  • Conduct guidelines
  • Maintaining the list of collaborators

The current list of TSC members is in the project README.

The TSC Charter governs the operations of the TSC. All changes to the Charter need approval by the OpenJS Foundation Cross-Project Council (CPC).

TSC meetings

The TSC meets in a Discord conference call or Discord thread. Each year, the TSC elects a chair to run the meetings.

Any community member can create a GitHub issue asking that the TSC review something.

The TSC may invite people to take part in a non-voting capacity.

During the meeting, the TSC chair ensures that someone takes minutes. After the meeting, the TSC chair ensures that someone opens a pull request with the minutes.

The TSC seeks to resolve as many issues as possible outside meetings using the webpack's governance repository issue tracker.

The process in the issue tracker is:

  • A TSC member opens an issue explaining the proposal/issue and @-mentions @webpack/tsc.
  • The proposal passes if, after 72 hours, there are two or more TSC voting member approvals and no TSC voting member opposition.
  • If there is an extended impasse, a TSC member may make a motion for a vote.

Consensus Seeking Process

The TSC follows a Consensus Seeking decision making model.

When an agenda item has appeared to reach a consensus, the moderator will ask "Does anyone object?" as a final call for dissent from the consensus.

If an agenda item cannot reach a consensus, a TSC member can call for either a closing vote or a vote to table the issue to the next meeting. The call for a vote must be approved by a majority of the TSC or else the discussion will continue. Simple majority wins.


This document is an adaption of the Node.js project Governance Model and the ESlint project Governance Model

Charter

webpack TSC Charter

Section 0. Guiding Principle

The webpack project is part of the OpenJS Foundation. The project operates transparently, openly, collaboratively, and ethically. Project proposals, timelines, and status must not merely be open, but also easily visible to outsiders.

Section 1. Scope

The webpack project is a highly flexible and efficient module bundler for modern JavaScript applications. Its primary purpose is to transform and bundle various modules (JavaScript, CSS, images, etc.) into a format suitable for web applications. Webpack focuses on enhancing the developer experience, providing optimizations for production environments, and enabling configurations to support a wide range of use cases and edge cases for specific projects.

With this, webpack not only simplifies the process of managing application dependencies, but it also offers tools to optimize performance, maintainability, and scalability. The webpack community contributes solutions to common challenges in modern web development, helping developers streamline their workflows and build robust applications.

1.1: In-scope

  • Bundling JavaScript files and their dependencies into a single output (or multiple outputs) for browser environments
  • Handling of asset files such as CSS, images, fonts, and other static resources
  • Optimization of assets for production, including minification, compression, and tree shaking (removal of unused code)
  • Enabling hot module replacement (HMR) for faster development feedback loops
  • Configuration and extensibility through plugins and loaders
  • Support for code splitting and lazy loading to enhance performance
  • Integrating with modern JavaScript frameworks (e.g., React, Vue, Angular)
  • Providing detailed build reports and debugging tools for development and production
  • Supporting multiple output formats (e.g., AMD, CommonJS, ES Modules) for compatibility with various environments
  • Community-driven tools and best practices provided through plugins and guides
  • Technical help and discussions via community platforms such as GitHub Discussions

In addition to the main repository, webpack (bundler), the organization maintains and manages several other core projects that are integral to the ecosystem such as webpack-dev-server, webpack-cli, and webpack-contrib projects.

These repositories, along with others housed within the github.com/webpack and github.com/webpack-contrib are owned by the webpack project.

1.2: Out-of-Scope

  • Testing frameworks (e.g., unit, integration, or end-to-end testing tools).
  • APIs and tools that uses webpack in any way and are not in the webpack organization.
  • Server-side rendering directly (although it can integrate with SSR frameworks).
  • webpack-related frameworks and libraries that operate in their own capacity.

Section 2. Relationship with OpenJS Foundation CPC.

Most large, complex open source communities have both a business and a technical governance model. Technical leadership for the projects within the OpenJS Foundation is delegated to the projects through their project charters by the OpenJS Cross Project Council (CPC). In the case of the webpack project, it is delegated to the webpack Technical Steering Committee ("TSC"). OpenJS Foundation's business leadership is the Board of Directors (the "Board").

This charter can only be amended with the approval of the CPC.

Section 3. Establishment of the TSC

TSC members can be either regular members or voting members. Regular members can attend meetings and participate in TSC discussions, but do not vote. Voting members can do everything regular members can do, and also have the ability to cast votes when consensus is not reached on an issue.

TSC memberships are not time-limited. There is no maximum size of the TSC. The TSC must have at least four voting members.

The TSC may add additional voting members to the TSC through meeting consensus. The consensus requires at least five TSC members to be present to approve a new voting member. A TSC member can be removed from the TSC by voluntary resignation or by consensus with at least five voting members to be present. A vote in a TSC meeting can be used to change a regular TSC member to a voting TSC member, or to change a voting TSC member to a regular TSC member.

No more than one-fourth of the TSC voting members may be affiliated with the same employer. If a change in TSC voting membership or a change of employment by a TSC voting member creates a situation where more than one-fourth of the TSC voting membership shares an employer, then the situation must be immediately remedied by the removal of voting member status from one or more TSC voting members affiliated with the over-represented employer(s).

The TSC shall meet regularly using tools that enable participation by the community (e.g. weekly on a Google Hangout On Air, or through any other appropriate means selected by the TSC). The meeting shall be directed by the TSC Chairperson. Responsibility for directing individual meetings may be delegated by the TSC Chairperson to any other TSC voting member. Minutes or an appropriate recording shall be taken and made available to the community through accessible public postings.

TSC voting members are expected to regularly participate in TSC meetings and issue triaging.

A TSC voting member is automatically converted to a TSC regular member if they do not participate in three consecutive TSC votes.

Section 4. Roles & Responsibilities of the TSC

Subject to such policies as may be set by the CPC, the TSC voting members are responsible for all technical development within the webpack project, including:

  • Setting release dates.
  • Release quality standards.
  • Technical direction.
  • Project governance and process.
  • GitHub repository management.
  • Conduct and maintain guidelines defined by the OpenJS Foundation Cross Project Council.
  • Maintaining the list of additional collaborators.
  • Development process and any coding standards.
  • Mediating technical conflicts between collaborators or webpack projects.

The TSC voting members will define webpack project's release vehicles.

Section 4.1. webpack Project Operations

The TSC voting members will establish and maintain a development process for the webpack project. The development process will establish guidelines for how the developers and community will operate. It will, for example, establish appropriate timelines for TSC review (e.g. agenda items must be published at least a certain number of hours in advance of a TSC meeting).

Note that project operations remain subject to any relevant policy or process specified by the OpenJS Foundation board or Cross Project Council.

Section 4.2. Decision-making, Voting, and/or Elections

Section 4.2.1. Elections

These processes are described in webpack's GOVERNANCE document.

Section 4.2.2. Decision Making

For webpack projects' decisions, Collaborators and TSC voting members shall operate under Lazy Consensus (consensus seeking). When an agenda item has appeared to reach a consensus, the moderator will ask "Does anyone object?" as a final call for dissent from the consensus. For all votes, a simple majority of all TSC voting members for, or against, the issue wins. A TSC voting member may choose to participate in any vote through abstention. Votes are needed to add new members, remove members from the TSC or deciding in project critical issues, such as roadmapping major versions of webpack core.

Section 5. Definitions

  • Project: a technical collaboration effort, e.g. a subsystem, that is organized through the webpack organization creation.

This work is a derivative of the Node.js Project TSC Charter.

Writer's Guide

아래에는 콘텐츠 편집 및 추가에 대해 알아야 할 모든 내용이 포함되어 있습니다. 편집이나 추가를 시작하기 전에 몇 가지 확인하세요. 때때로 가장 어려운 부분은 콘텐츠가 있어야 할 위치를 찾고 콘텐츠가 이미 존재하는지 여부를 결정하는 것입니다.

Process

  1. 글이 링크되어 있다면 관련된 이슈를 확인하세요.
  2. 편집을 누르고 구조를 확장하세요.
  3. 변경점들을 Pull Request에 생성하세요.

YAML Frontmatter

모든 글들은 상단에 YAML Frontmatter로 쓰인 작은 섹션을 포함합니다.

---
title: My Article
group: My Sub-Section
sort: 3
contributors:
  - [github username]
related:
  - title: Title of Related Article
    url: [url of related article]
---

각각에 대해 알아보겠습니다.

  • title: 글의 제목입니다.
  • group: 하위 섹션의 제목입니다.
  • sort: 해당 섹션 (또는) 하위 섹션 내에서 글의 순서입니다.
  • contributors: 글에 기여한 사람들이 GitHub username 리스트입니다.
  • related: 관련된 읽을거리 또는 유용한 예시입니다.

related는 페이지 하단에 Further Reading 섹션을 생성하고 contributors는 그 아래에 Contributors 섹션을 생성합니다. 글을 편집하고 인정받고 싶다면 주저하지 말고 GitHub 사용자 이름을 contributors 목록에 추가하세요.

Article Structure

  1. 간략한 소개 - 어떤 것을 왜 하였는지에 대한 아이디어를 적은 한두 문단입니다.
  2. 남은 콘텐츠 개요 – 콘텐츠가 표시되는 방식입니다.
  3. 주요 콘텐츠 - 주요 내용들을 말하세요.
  4. 결론 - 내용들을 정리하고 주요 포인트들을 요약합니다.

Typesetting

  • Webpack은 문장의 시작 부분에 대문자 W로 작성할 수 있습니다. (출처)
  • 로더는 역 따옴표로 묶여 있으며 kebab-cased입니다. 다음은 예시 입니다. css-loader, ts-loader, …
  • 플러그인은 백틱 및 camel-cased로 묶입니다. 다음은 예시 입니다. BannerPlugin, NpmInstallWebpackPlugin, …
  • "webpack 2"를 사용하여 특정 Webpack 버전을 나타냅니다("webpack v2").
  • ES5 사용; ES2015, ES2016, ... ECMAScript 표준 참조(ES6, ES7)

Formatting

Code

Syntax: ```javascript … ```

function foo() {
  return 'bar';
}

foo();

Quotation

코드 스니펫과 프로젝트 파일(.jsx, .scss 등)에 작은따옴표를 사용하세요.

- import webpack from "webpack";
+ import webpack from 'webpack';

그리고 아래는 인라인 백틱 안에서의 예시입니다.

correct

값을 'index.md'로 설정...

incorrect

값을 "index.md"로 설정...

Lists

  • Boo
  • Foo
  • Zoo

목록은 알파벳순으로 정렬되어야 합니다.

Tables

ParameterExplanationInput TypeDefault Value
--debug로더를 디버그 모드로 변환booleanfalse
--devtool번들 리소스에 대한 소스맵 유형 정의string-
--progress백분율로 컴파일 진행률 출력booleanfalse

테이블도 알파벳순으로 정렬해야 합니다.

Configuration Properties

설정 속성도 알파벳순으로 정렬해야 합니다.

  • devServer.compress
  • devServer.hot
  • devServer.static

Quotes

Blockquote

Syntax: >

이것은 Blockquote입니다.

Tip

Syntax: T>

Syntax: W>

Syntax: ?>

Assumptions and simplicity

문서를 작성할 때 가정하지 마세요.

- 프로덕션을 위해 번들을 최적화하는 방법을 이미 알고 있을 수 있습니다...
+ 이미 우리는 [프로덕션 가이드](/guides/production/)에서 배웠습니다...

모든 것이 단순하다고 가정하지 마세요. '그냥', '간단하게'와 같은 단어를 피하세요.

- 간단히 명령을 실행하세요...
+ `command-name` 명령을 실행하세요...

Configuration defaults and types

문서를 쉽게 이해할 수 있고 잘 작성할 수 있도록 항상 모든 문서 옵션에 유형과 기본값을 제공하세요. 저희는 문서화된 옵션은 제목으로 작성한 후 유형과 기본값을 추가합니다.

configuration.example.option

string = 'none'

여기서 = 'none'은 주어진 옵션에 대한 기본값이 'none'임을 의미합니다.

string = 'none': 'none' | 'development' | 'production'

여기서 : 'none' | 'development' | 'production'에는 가능한 유형 값을 열거합니다. 이 경우에는 'none', 'development''production'의 세 가지 문자열을 사용할 수 있습니다.

주어진 옵션에 대해 사용 가능한 모든 유형을 나열하려면 유형 사이에 공백을 사용하세요.

string = 'none': 'none' | 'development' | 'production' boolean

배열을 표시하려면 대괄호를 사용하세요.

string [string]

array에 여러 유형이 허용되는 경우 쉼표를 사용합니다.

string [string, RegExp, function(arg) => string]

함수를 표시하려면 사용 가능한 인수도 나열하세요.

function (compilation, module, path) => boolean

여기서 (compilation, module, path)에는 제공된 함수가 수신할 인수를 나열하고 => boolean은 함수의 반환 값이 boolean이어야 함을 의미합니다.

플러그인을 사용 가능한 옵션 값 유형으로 표시하려면 Plugin의 camel-cased 형식의 제목을 사용하세요.

TerserPlugin [TerserPlugin]

이는 옵션이 하나 또는 소수의 TerserPlugin 인스턴스를 예상한다는 것을 의미합니다.

숫자를 표시하려면 number를 사용하세요.

number = 15: 5, 15, 30

객체를 표시하려면 object를 사용하세요.

object = { prop1 string = 'none': 'none' | 'development' | 'production', prop2 boolean = false, prop3 function (module) => string }

객체의 키가 여러 유형을 가질 수 있는 경우 |를 사용하여 나열하세요. 다음은 prop1이 문자열과 문자열 배열 모두일 수 있는 예입니다.

object = { prop1 string = 'none': 'none' | 'development' | 'production' | [string]}

이를 통해 기본값, 열거 및 기타 정보를 표시할 수 있습니다.

객체의 키가 동적이며 사용자 정의된 경우 <key>를 사용하여 설명합니다.

object = { <key> string }

Options shortlists and their typing

때때로 목록에 있는 객체와 함수의 특정 속성을 설명하고 싶을 때가 있습니다. 해당하는 경우 속성이 등록된 목록에 직접 입력을 추가합니다.

  • madeUp (boolean = true): short description
  • shortText (string = 'i am text'): another short description

예제는 EvalSourceMapDevToolPlugin 페이지의 options 섹션에서 찾을 수 있습니다.

Adding links

절대적 URL(예: https://webpack.js.org/concepts/mode/) 대신 상대적 URL(예: /concepts/mode/)을 사용하여 자체 콘텐츠를 연결하세요.

Member Expectations

All participants in the webpack project must follow the Code of Conduct. There are further expectations for members of the TSC.

When decisions are made within the established guidelines and policies of the project, those in leadership roles have a responsibility to uphold and respect the decision even if they disagree with it. This is especially important in external communications, for example in social media. Should the member be unwilling or unable to do so, then they should resign their leadership position. This does not mean that decisions cannot be revisited and discussed within the team at a later time.

Everyone participating in the webpack project must conduct themselves in a professional and respectful manner in accordance with our Code of Conduct. In addition, some general guidelines for leadership group members include:

  • Remediate quickly when you realize you made a mistake. Leaders are human, and they will make mistakes. However they should act swiftly to acknowledge mistakes and correct them.
  • Aim to remediate first and then discuss. If other members of the team express concerns about actions, acknowledge their concerns by stopping the actions in question and then discuss within the team to come to a common agreement.
  • Treat all community members with respect, consideration, and highest standards of ethical conduct.
  • Value a diversity of views and opinions. Avoid preferential treatment, and hold everyone (including ourselves) accountable to the same set of standards. Everyone gets to speak up.
  • Deal with issues directly with the person in question. Resist complaining about others in the project in a public sphere.
  • Build trust by keeping your promises.
  • Be the model of accountability and leadership. Provide the example of ownership and stewardship that everyone can follow to success.
  • Commit to ongoing development and learning best practices for governing.
  • Criticize ideas rather than people, discussing any concerns in person whenever possible, and taking responsibility for our statements.

While the guidelines above focus primarily on the spaces where we participate in official foundation work (GitHub, IRC, meetings, conferences), it is important to recognize that the public behavior of members also reflects on the webpack project.

If you're interested in an introduction to diversity, inclusion, and unconscious bias, try this free training offered by our partners at the Linux Foundation.

If it appears that any member of the project leadership is acting outside of the expectations set above please refer to our moderation policy which outlines the process of making an official complaint.


This document is an adaption of the Node.js project Member Expectations

Writing a Loader

로더는 함수를 export 하는 node 모듈입니다. 이 함수는 리소스가 로더에 의해 변형되어야 할 때 호출됩니다. 주어진 함수는 같이 제공되는 this 컨텍스트를 사용해 Loader API에 접근할 것입니다.

Setup

다른 타입의 로더와 사용법과 예시를 살펴보기 전에, 로컬에서 개발하고 테스트할 수 있는 세 가지 방법을 봅시다.

단일 로더를 테스트하기 위해, rule object 내의 로컬 파일을 resolve하기 위한 path를 사용할 수 있습니다.

webpack.config.js

const path = require('path');

module.exports = {
  //...
  module: {
    rules: [
      {
        test: /\.js$/,
        use: [
          {
            loader: path.resolve('path/to/loader.js'),
            options: {
              /* ... */
            },
          },
        ],
      },
    ],
  },
};

다중 로더를 테스트하기 위해, webpack이 로더를 검색할 위치를 업데이트하기 위한 resolveLoader.modules 설정을 활용할 수 있습니다. 예를 들어, 프로젝트에서 로컬 /loaders 디렉터리를 생성했다고 가정해봅시다.

webpack.config.js

const path = require('path');

module.exports = {
  //...
  resolveLoader: {
    modules: ['node_modules', path.resolve(__dirname, 'loaders')],
  },
};

그런데, 이미 로더에 대한 독립된 저장소와 패키지를 생성했다면, 테스트하려는 프로젝트와 npm link해줄 수 있습니다.

Simple Usage

단일 로더가 리소스에 적용되었을 때, 로더는 오직 하나의 파라미터(리소스 파일의 콘텐츠를 담고 있는 문자열)와 호출됩니다.

동기 로더는 변형된 모듈을 대표하는 하나의 값을 return 할 수 있습니다. 더 복잡한 경우에서, 로더는 this.callback(err, values...) 함수를 사용함으로써 여러 값을 반환할 수 있습니다. 에러는 this.callback 함수를 통과하거나 동기 로더에 throw 됩니다.

로더는 하나 혹은 두 개의 값을 반환해야 합니다. 첫 값은 문자열 혹은 버퍼로서의 JavaScript 코드의 결과입니다. 두 번째 선택적 값은 JavaScript 객체인 SourceMap입니다.

Complex Usage

다중 로더가 연결될 때, 역순(배열 형식에 따라 오른쪽에서 왼쪽 혹은 아래에서 위)으로 실행되는지 기억해야 합니다.

  • 처음이라 불리는 마지막 로더는 원상태의 리소스의 콘텐츠가 통과될 것입니다.
  • 마지막이라 불리는 첫 로더는 JavaScript와 선택적 소스맵을 반환해야 합니다.
  • 사이에 있는 로더는 체인에 있는 이전 로더의 결과와 함께 실행됩니다.

다음 예시에서, foo-loader는 raw 리소스를 통과할 것이고, bar-loaderfoo-loader의 출력을 하고 최종 변형된 모듈과 필요하다면 소스맵을 반환하겠습니다.

webpack.config.js

module.exports = {
  //...
  module: {
    rules: [
      {
        test: /\.js/,
        use: ['bar-loader', 'foo-loader'],
      },
    ],
  },
};

Guidelines

다음 가이드라인은 로더를 작성할 때 지켜져야 합니다. 중요도 측면에서 순서가 지정되며, 일부는 특정 시나리오에서 적용됩니다. 자세한 내용은 세부 섹션을 참고하세요.

  • 단순하게 하세요.
  • chaining을 활용하세요.
  • 모듈의 출력을 내보내세요.
  • stateless인지 확인하세요.
  • 로더 유틸리티를 사용하세요.
  • 로더 의존성을 표시하세요.
  • 모듈 의존성을 해석하세요.
  • 공통된 코드를 추출하세요.
  • 절대 경로를 지양하세요.
  • peer dependencies를 사용하세요.

Simple

로더는 오직 하나의 일만 수행해야 합니다. 로더를 유지 보수하기 쉽게 만들 뿐만 아니라, 더 많은 시나리오에서 사용할 수 있도록 체인으로 묶을 수 있습니다.

Chaining

로더가 함께 연결될 수 있다는 사실을 활용하세요. 다섯 가지의 일을 처리하는 하나의 로더를 작성하는 것 대신에, 수고를 덜 다섯 개의 간단한 로더들을 작성하세요. 로더를 분할하는 것은 각각의 로더를 간단히 유지할 수 있을 뿐만 아니라 생각지도 못한 일에 사용될 수 있게 해줄 수 있습니다.

로더 옵션 또는 쿼리 파라미터를 통해 지정된 데이터로 템플릿 파일을 렌더링하는 경우를 생각해 봅시다. 소스에서 템플릿을 컴파일 하는 싱글 로더로 작성되고, 그를 실행하고 HTML 코드를 포함하고 있는 문자열을 export 하는 모듈을 반환할 수도 있습니다. 하지만, 가이드라인에 따르면, apply-loader는 다른 오픈 소스 로더와 연결될 수 있을 때만 존재합니다.

  • pug-loader: 템플릿을 함수를 export 하는 모듈로 전환합니다.
  • apply-loader: 로더 옵션으로 함수를 실행시키고, raw HTML을 반환합니다.
  • html-loader: HTML을 받아들이고 유효한 JavaScript 모듈을 출력합니다.

Modular

출력을 모듈식으로 유지하세요. 모듈을 생성한 로더는 일반 모듈로써 같은 디자인 요소를 반영해야 합니다.

Stateless

로더가 모듈 변형 사이에 상태를 유지하지 않는지 확인하세요. 각 실행은 항상 컴파일된 다른 모듈 및 동일한 모듈의 이전 컴파일과는 독립적이어야 합니다.

Loader Utilities

다양한 유용한 도구를 제공하는 loader-utils 패키지를 활용하세요. loader-utils과 함께, schema-utils 패키지는 로더 옵션 유효성에 기반한 일관된 JSON 스키마를 위해 사용돼야 합니다. 여기 둘 다 활용하는 간단한 예시가 있습니다.

loader.js

import { urlToRequest } from 'loader-utils';
import { validate } from 'schema-utils';

const schema = {
  type: 'object',
  properties: {
    test: {
      type: 'string',
    },
  },
};

export default function (source) {
  const options = this.getOptions();

  validate(schema, options, {
    name: 'Example Loader',
    baseDataPath: 'options',
  });

  console.log('The request path', urlToRequest(this.resourcePath));

  // 소스에 몇 가지의 변형을 적용하세요...

  return `export default ${JSON.stringify(source)}`;
}

Data Sharing

Webpack에서는 로더를 체인화하여 체인의 후속 로더와 데이터를 공유할 수 있습니다. 이를 위해서는 raw 로더에서 this.callback 메소드를 사용하여 콘텐츠(소스 코드)와 함께 데이터를 전달할 수 있습니다. Raw 로더의 기본 내보내기 함수에서는 this.callback의 네 번째 인수를 사용하여 데이터를 전달할 수 있습니다.

export default function (source) {
  const options = getOptions(this);
  // Pass data using the fourth argument of this.callback
  this.callback(null, `export default ${JSON.stringify(source)}`, null, {
    some: data,
  });
}

위의 예에서 this.callback의 네 번째 인수에 있는 some 속성은 다음 체인 로더에 데이터를 전달하는 데 사용됩니다.

Loader Dependencies

로더가 외부 리소스(예를 들면, 파일 시스템으로부터 읽는 것)를 사용한다면, 반드시 표기해야 합니다. 이 정보는 캐시 가능한 로더를 무효로 하고 읽기 모드로 다시 컴파일하기 위해 사용됩니다. addDependency 메소드를 사용해서 완수하는 방법의 간략한 예시가 있습니다.

loader.js

import path from 'path';

export default function (source) {
  var callback = this.async();
  var headerPath = path.resolve('header.js');

  this.addDependency(headerPath);

  fs.readFile(headerPath, 'utf-8', function (err, header) {
    if (err) return callback(err);
    callback(null, header + '\n' + source);
  });
}

Module Dependencies

모듈의 타입에 따라, 특정한 의존성을 사용하는 다른 스키마가 있을지도 모릅니다. 예를 들어, CSS에서 @importurl(...) 구문이 사용됩니다. 이런 의존성은 모듈 시스템에 의해 결정되어야 합니다.

둘 중 하나의 방법으로 할 수 있습니다.

  • require 구문으로 변형
  • 경로를 결정하기 위해 this.resolve 함수를 사용

css-loader는 처음으로 접근하기에 좋은 예시입니다. 다른 스타일시트에 대해서 @import 구문을 require로 대체하고, 참조된 파일에 대해서 url(...)require로 바꿈으로써, 의존성들을 require으로 변형합니다.

less-loader의 예시에서, 모든 .less파일은 변수와 믹스인 추정을 위해 반드시 한 번에 컴파일되어야 하므로 각 @importrequire로 바꿀 수 없습니다. 그러므로, less-loader는 사용자 경로 해석 로직으로 더 적은 컴파일러를 확장합니다. 그런 다음 두 번째 접근 방식인 this.resolve를 활용하여 webpack을 통해 의존성을 해결할 수 있습니다.

Common Code

로더가 처리하는 모든 모듈 안의 공통적인 코드가 생성되지 않도록 하세요. 대신, 로더 안에 런타임 파일을 만들고, 해당 공유 모듈에 require를 생성하세요.

src/loader-runtime.js

const { someOtherModule } = require('./some-other-module');

module.exports = function runtime(params) {
  const x = params.y * 2;

  return someOtherModule(params, x);
};

src/loader.js

import runtime from './loader-runtime.js';

export default function loader(source) {
  // 커스텀 로더 로직

  return `${runtime({
    source,
    y: Math.random(),
  })}`;
}

Absolute Paths

절대 경로는 프로젝트의 루트가 이동될 때 해싱이 끊어지므로 모듈 코드에 삽입하지 마세요. 아래 코드를 사용하여 절대 경로를 상대 경로로 변환할 수 있습니다.

// `loaderContext`는 로더 함수 내부의 `this`와 동일합니다.
JSON.stringify(
  loaderContext.utils.contextify(
    loaderContext.context || loaderContext.rootContext,
    request
  )
);

Peer Dependencies

작업하고 있는 로드가 다른 패키지의 간단한 wrapper라면, peerDependency로써 패키지를 포함할 수 있습니다. 이런 접근은 애플리케이션 개발자가 필요하다면 package.json안의 정확한 버전을 지정하도록 해줍니다.

예를 들어, sass-loader는 peer dependency와 같이 node-sass를 지정합니다.

{
  "peerDependencies": {
    "node-sass": "^4.0.0"
  }
}

Testing

로더를 작성하고 위의 가이드라인에 따라 로컬에서 실행하도록 설정했습니다. 다음은 무엇일까요? 로더가 예상대로 작동하는지 확인하기 위해 유닛 테스트 예시를 살펴보겠습니다. 이를 위해 Jest 프레임워크를 사용할 예정입니다. 또한 import/exportasync/await를 사용할 수 있는 babel-jest와 일부 프리셋도 설치할 것입니다. 먼저 devDependencies로 설치하고 저장하겠습니다.

npm install --save-dev jest babel-jest @babel/core @babel/preset-env

babel.config.js

module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          node: 'current',
        },
      },
    ],
  ],
};

로더가 .txt파일을 처리하고 어느 인스턴스의 [name]을 로더에 주어진 name 옵션으로 바꿀 것입니다. 그러고 나서, 기본 출력으로써 문자를 담고 있는 유효한 JavaScript 모듈을 출력할 것입니다.

src/loader.js

export default function loader(source) {
  const options = this.getOptions();

  source = source.replace(/\[name\]/g, options.name);

  return `export default ${JSON.stringify(source)}`;
}

다음 파일을 처리하기 위해 이 로더를 사용하겠습니다.

test/example.txt

Hey [name]!

webpack을 실행하기 위해 Node.js APImemfs 사용할 다음 단계에 세심한 주의를 기울이세요. 이는 디스크에 output을 출력하는 것을 막고, 변형한 모듈을 파악하기 위해 사용할 수 있는 stats 데이터에 접근할 수 있도록 할 것입니다.

npm install --save-dev webpack memfs

test/compiler.js

import path from 'path';
import webpack from 'webpack';
import { createFsFromVolume, Volume } from 'memfs';

export default (fixture, options = {}) => {
  const compiler = webpack({
    context: __dirname,
    entry: `./${fixture}`,
    output: {
      path: path.resolve(__dirname),
      filename: 'bundle.js',
    },
    module: {
      rules: [
        {
          test: /\.txt$/,
          use: {
            loader: path.resolve(__dirname, '../src/loader.js'),
            options,
          },
        },
      ],
    },
  });

  compiler.outputFileSystem = createFsFromVolume(new Volume());
  compiler.outputFileSystem.join = path.join.bind(path);

  return new Promise((resolve, reject) => {
    compiler.run((err, stats) => {
      if (err) reject(err);
      if (stats.hasErrors()) reject(stats.toJson().errors);

      resolve(stats);
    });
  });
};

이제, 마지막으로, 테스트를 작성하고 npm script에 실행하도록 추가할 수 있습니다.

test/loader.test.js

/**
 * @jest-environment node
 */
import compiler from './compiler.js';

test('Inserts name and outputs JavaScript', async () => {
  const stats = await compiler('example.txt', { name: 'Alice' });
  const output = stats.toJson({ source: true }).modules[0].source;

  expect(output).toBe('export default "Hey Alice!\\n"');
});

package.json

{
  "scripts": {
    "test": "jest"
  },
  "jest": {
    "testEnvironment": "node"
  }
}

모든 것이 갖춰져 있으면, 그것을 실행하고 새로운 로더가 테스트를 통과했는지 볼 수 있습니다.

 PASS  test/loader.test.js
  ✓ Inserts name and outputs JavaScript (229ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.853s, estimated 2s
Ran all test suites.

성공했습니다! 이제 자신만의 로더를 개발, 테스트 및 배포할 준비가 되어 있어야 합니다. 창작물을 커뮤니티의 다른 사람들과 공유해 주시기 바랍니다.

Moderation Policy

Moderation policy

If you are not a member of the webpack GitHub Organization and wish to submit a moderation request, please see Requesting Moderation

Applicability

This policy applies to all repositories under the webpack and webpack-contrib GitHub Organizations and all webpack Working Groups. This policy also applies to the webpack Slack Community, supported by the Admin team of the Slack organization.

Terms

  • Collaborator refers to any individual with configured triage role or higher in any webpack GitHub organizations repositories. See GitHub's Repository roles documentation for more information.
  • TSC refers to the webpack Technical Steering Committee.
  • Post refers to the content and titles of any issue, pull request, comment, discussion, or wiki page.
  • Moderate means to modify, lock, or delete one or more Posts to correct or address Code of Conduct violations.
  • Remove refers to the act of removing the configured write (commit) permissions for an individual Collaborator's GitHub account from all webpack GitHub Organizations repositories as well as removing the account from the webpack GitHub Organizations membership.
  • Block refers to the act of prohibiting an individual GitHub account from any further participation in the webpack GitHub Organizations. A block may be temporary or indefinite.
  • Requester refers to an individual requesting Moderation on a Post.

Grounds for Moderation

Any Post in violation of the webpack Code of Conduct is subject to Moderation.

The TSC is responsible for deciding what constitutes inappropriate behavior that may be subject to Moderation.

Requesting Moderation

Anyone may request Moderation of a Post. Requesting Moderation of a Post can be accomplished in one of four ways:

  • Via the webpack-security@openjsf.org email address,
  • Via private email to individual TSC members,
  • Via a new Post in the same thread as the Post being requested for Moderation,
  • Via a new Post in the private webpack/moderation repository.

Note that Collaborators may Moderate non-Collaborator Posts at any time without submitting an initial request (see: Non-Collaborator Posts).

Use of the webpack-security@openjsf.org email address -- or private email to individual TSC members -- is appropriate when the individual requesting the Moderation does not feel comfortable directly or publicly making the request. All emails sent to the webpack-security@openjsf.org address are currently forwarded to all members of the TSC.

Requests should contain as much information and context as possible, including the URL and a screenshot of the Post in question. Screenshots may be modified to obscure obscene or offensive content.

External public venues or social media services such as Twitter must never be used to request Moderation.

Collaborators must never discuss the specific details of a Moderation request in any public forum or any social media service outside of the webpack GitHub Organization.

Note that quoting the original content of a Post within a Moderation request or webpack/moderation repository issue is not a violation of the Code of Conduct. However, discretion is advised when including such quotes in requests posted to public repositories.

Requests for Moderation that do not appear to have been submitted in good faith with intent to address a legitimate Code of Conduct violation will be ignored.

Consideration of Intent

Before Moderating a Post, Collaborators should carefully consider the possible intent of the author. It may be that the author has simply made an error or is not yet familiar with the Code of Conduct; or it may be that cultural differences exist, or that the author is unaware that certain content is inappropriate. In such cases, the author should be given an opportunity to correct any error that may have been made.

Note, however, that unfamiliarity with the Code of Conduct does not excuse a Post from Moderation.

Guidelines and Requirements

  • All Posts are expected to respect the webpack Code of Conduct.
  • Any Collaborator with triage permission to a given repository (except webpack/moderation) may Moderate Posts within that repository's issue tracker. Only the TSC is allowed to moderate posts on webpack/moderation.
  • The TSC serves as the final arbiter for all Moderation issues.
  • TSC members may Remove or Block an individual from the webpack GitHub Organizations.
  • For any Removal or Blocking action, an issue describing the reasons for the action, and identifying the Github account being acted upon, must be posted to the Moderation Repository with an explanation provided by the Moderation Team member performing the action.
  • Any individual Blocked from the webpack GitHub Organizations will be recommended for exclusion from any webpack Foundation sponsored event or activity.
  • Minor edits to the formatting of a Post or to correct typographical errors are not "Moderation". Such edits and their intent must still be documented with a short note indicating who made the edit and why.

Collaborator Posts

  • Prior to Moderating any Post authored by a Collaborator, the author must be given a reasonable opportunity to modify or remove the Post on their own.
  • If the author of the Post disagrees that Moderation is required, the matter can be escalated to the TSC for resolution. In such cases, no Moderation action may be taken until a decision by the TSC is made.
  • When Moderating any Post authored by another Collaborator, the moderating Collaborator must:
    • Explain the justification for Moderating the post,
    • Identify all changes made to the Post, and
    • Identify the steps previously taken to resolve the issue.
    • If the Moderation action included Blocking, an indication of whether the Block is temporary or indefinite is required, along with an issue posted to the moderation repository justifying the action.
  • Explanations of Moderation actions on Collaborator Posts must be provided in:
    • A new post within the original thread, or
    • A new issue within the private webpack/moderation repository.
  • Any Collaborator habitually violating the Code of Conduct or this Moderation policy may be Blocked temporarily or, in extreme cases, Removed and Blocked indefinitely.

Non-Collaborator Posts

  • Posts authored by non-Collaborators are always subject to immediate Moderation by any Collaborator if the content is intentionally disruptive or in violation of the Code of Conduct.
  • When moderating non-Collaborator posts, the moderating Collaborator must:
    • Explain the justification for Moderating the post, and
    • Identify all changes made to the Post.
    • If the Moderation action included Blocking, an indication of whether the Block is temporary or indefinite is required, along with a note justifying the action.
  • If an explanation of a Moderation action for a non-Collaborator Post is provided, it must be provided in:
    • The original Post being modified (as replacement or appended content),
    • A new post within the original thread, or
    • A new issue within the private webpack/moderation repository.
  • Moderation of Posts authored by non-Collaborators may result in those non-Collaborators being Blocked temporarily or indefinitely from further participation in the webpack GitHub organizations.
  • If it is clear that there is no intention to collaborate in good faith, it is possible to hide comments of non-Collaborators. In that case there is an exception to the reporting requirement described above.
  • Accounts that are reasonably believed to be bots (other than bots authorized by the TSC) are subject to immediate Blocking.
  • Issues, pull requests, discussions, and comments that are spam (job posting, service advertising, etc.) are subject to immediate moderation.
  • Issues, pull requests, discussions, and comments that are believed to be LLM-generated (e.g a PR coming from a new contributor changing a single file without clear motivation) should be closed with a comment such as "It seems you are using a LLM, please stop, this is not bringing any value and is wasting our time. If you are not using one, please read and follow our contributing guidelines." Report the user to the moderation repository so they get blocked if they do it again.
  • Collaborators may use the Hide feature in the GitHub interface for off-topic posts by non-Collaborators.
  • TSC members can delete any issues or comments posted by accounts that have been deleted by GitHub. These accounts show up in the GitHub interface as user ghost. There is no need to screenshot or document these deletions.

There are a few examples of moderating non-Collaborator posts:

Scenario 1:

  • A non-Collaborator posts a comment that indicates that they are a bot.
  • A collaborator sees the post and hides it.
  • No further action is necessary.

Scenario 2:

  • A non-Collaborator posts a comment that is against the Code of Conduct.
  • A Collaborator sees the comment and asks the author to edit it.
  • The author refuses to edit their comment.
  • The Collaborator deletes the comment and posts an issue in the moderation repository explaining their actions.

Scenario 3:

  • A non-Collaborator opens a pull request with comments indicating they are a bot.
  • A Collaborator sees that pull requests, closes it, deletes the comments and posts an issue in the moderation repository explaining their actions.
  • A TSC member sees the issue and decides to block the user from the organization.

Scenario 4:

  • A non-Collaborator posts a comment on an old commit that is against the Code of Conduct.
  • A Collaborator sees the comment, takes a screenshot, and deletes it.
  • The Collaborator posts an issue in the moderation repository explaining their actions.

Temporary Interaction Limits

The TSC may, at their discretion, choose to enable GitHub's Temporary Interaction Limits on any GitHub repository in the webpack GitHub Organization.

Any Collaborator may request that the TSC enable the Temporary Interaction Limits by posting an issue to the moderation repository. If the TSC chooses not to do so, then a comment explaining why that decision was made must be added to the moderation repository thread.

Temporary and Indefinite Blocks

A Temporary Block is time limited, with the timeframe decided on by the Moderation Team at the time of issuing, depending on the severity of the issue. Recommended default options are 24-hour, 48-hour, and 7-day periods.

An Indefinite Block is set for an unspecified period of time and may only be lifted for an individual through a simple majority vote of the Moderation Team.

Privacy of the webpack/moderation Repository

The webpack/moderation Repository is used to discuss the potentially sensitive details of any specific moderation issue. The repository is private but accessible to all Collaborators. The details of any issue discussed within the webpack/moderation repository are expected to remain confidential and are not to be discussed in any public forum or social media service.

Any Collaborator found to be violating the privacy of the webpack/moderation repository by repeatedly sharing or discussing the details of webpack/moderation issues in any public forum or social media service risks being permanently removed from the webpack GitHub organizations.

Escalation of Issues

Moderation issue disputes not involving a TSC member may be escalated to the TSC for review by tagging the original issue, pull request, or associated webpack/moderation repository. Any such Moderation action may be overturned through a TSC vote.

TSC members directly involved in a Moderation issue (as either the Requester or author of the Post in question) are required to recuse themselves from any decisions required to resolve the issue.

Moderation disputes involving TSC members, including questions of whether a TSC member has violated the Code of Conduct, shall be referred to an Independent Mediator selected by the OpenJS Foundation.

Modifications to This Policy

Modifications to this policy are subject to approval by the TSC. When modifications are proposed, if there are no objections after 72 hours, the modifications are accepted. If there any objections to any proposed change, a TSC vote in favor of the change is required.


This document is an adaption of the Node.js project Moderation Policy

Writing a Plugin

플러그인은 서드파티 개발자들에게 webpack 엔진의 모든 잠재력을 보여줍니다. 단계별로 빌드 callback을 사용하여 개발자들은 webpack의 빌드 프로세스에 자신만의 행동을 도입할 수 있습니다. 플러그인을 빌드하는 것은 로더를 빌딩 하는 것보다 조금 더 진보되었습니다. 왜냐하면, 플러그인은 몇몇 webpack의 low-level에 내장된 훅을 이해할 필요가 있기 때문입니다. 이제 소스 코드를 읽어볼 준비를 해봅시다!

Creating a Plugin

Webpack용 plugin은 다음과 같이 구성됩니다.

  • JavaScript function 또는 JavaScript class로 이름을 붙입니다.
  • 프로토타입에서 apply 메소드를 정의합니다.
  • 특정한 이벤트 훅으로 지정합니다.
  • webpack 내부에 있는 인스턴스의 특정한 데이터를 처리합니다.
  • 기능적으로 완벽해지면 webpack에서 제공하는 callback을 호출합니다.
// A JavaScript class.
class MyExampleWebpackPlugin {
  // `apply`를 compiler를 인자로 받는 프로토타입 메소드로 정의합니다.
  apply(compiler) {
    // attach할 이벤트 훅을 지정합니다.
    compiler.hooks.emit.tapAsync(
      'MyExampleWebpackPlugin',
      (compilation, callback) => {
        console.log('This is an example plugin!');
        console.log(
          'Here’s the `compilation` object which represents a single build of assets:',
          compilation
        );

        // Webpack에서 제공되는 플러그인 API를 사용하여 빌드를 처리합니다.
        compilation.addModule(/* ... */);

        callback();
      }
    );
  }
}

Basic plugin architecture

플러그인은 apply라는 프로토타입 메소드로 인스턴스화 된 객체입니다. 이러한 apply 메소드는 플러그인을 설치하는 동안 webpack 컴파일러에 의해 한번 호출됩니다. apply 메소드는 컴파일러 callback에 대해 접근 권한을 부여하는 기본 webpack 컴파일러에 의해 참조됩니다. 플러그인의 구조는 다음과 같습니다.

class HelloWorldPlugin {
  apply(compiler) {
    compiler.hooks.done.tap(
      'Hello World Plugin',
      (stats /* 훅의 탭이 끝나면 stats는 인자로 통과됩니다.*/) => {
        console.log('Hello World!');
      }
    );
  }
}

module.exports = HelloWorldPlugin;

그런 다음에 플러그인을 사용하려면 webpack의 설정인 plugins 배열에 인스턴스를 포함해야합니다.

// webpack.config.js
var HelloWorldPlugin = require('hello-world');

module.exports = {
  // ... 여기서 구성을 설정할 것 ...
  plugins: [new HelloWorldPlugin({ options: true })],
};

플러그인 옵션을 통해 전달되는 옵션의 유효성을 확인하려면 schema-utils를 사용하세요. 다음은 사용 예제입니다.

import { validate } from 'schema-utils';

// options 객체에 대한 schema
const schema = {
  type: 'object',
  properties: {
    test: {
      type: 'string',
    },
  },
};

export default class HelloWorldPlugin {
  constructor(options = {}) {
    validate(schema, options, {
      name: 'Hello World Plugin',
      baseDataPath: 'options',
    });
  }

  apply(compiler) {}
}

Compiler and Compilation

플러그인 개발 중 가장 중요한 두 개의 리소스는 compilercompilation 객체입니다. 두 가지의 역할을 이해하는 것은 webpack 엔진을 확장하는 첫 번째 단계입니다.

class HelloCompilationPlugin {
  apply(compiler) {
    // callback 함수에 인자로 compilation을 제공하는 훅으로 compliation 훅을 탭 합니다.
    compiler.hooks.compilation.tap('HelloCompilationPlugin', (compilation) => {
      // 이제 컴파일을 통해 이용할 수 있는 다양한 훅들을 이용할 수 있습니다.
      compilation.hooks.optimize.tap('HelloCompilationPlugin', () => {
        console.log('Assets are being optimized.');
      });
    });
  }
}

module.exports = HelloCompilationPlugin;

compiler, compilation 그리고 다른 중요한 객체에서 사용 가능한 훅의 목록은 플러그인 API 문서를 참고해 주세요.

Async event hooks

일부 플러그인 훅은 비동기입니다. 이를 탭 하려면, 동기로 동작하는 tap 메소드를 사용하거나 비동기 메소드인 tapAsync 또는 tapPromise 메소드를 사용할 수 있습니다.

tapAsync

tapAsync 메소드를 사용하여 플러그인을 탭해야 할 경우 함수에서 마지막 인자로 제공되는 callback 함수를 호출해야 할 필요가 있습니다.

class HelloAsyncPlugin {
  apply(compiler) {
    compiler.hooks.emit.tapAsync(
      'HelloAsyncPlugin',
      (compilation, callback) => {
        // Do something async...
        setTimeout(function () {
          console.log('Done with async work...');
          callback();
        }, 1000);
      }
    );
  }
}

module.exports = HelloAsyncPlugin;

tapPromise

플러그인에 탭 하기 위해 tapPromise를 사용할 때, 동기식 작업이 완료될 때의 해석 promise를 반드시 반환해야 할 필요가 있습니다.

class HelloAsyncPlugin {
  apply(compiler) {
    compiler.hooks.emit.tapPromise('HelloAsyncPlugin', (compilation) => {
      // 끝났을 때 해석을 반환해야 합니다..
      return new Promise((resolve, reject) => {
        setTimeout(function () {
          console.log('Done with async work...');
          resolve();
        }, 1000);
      });
    });
  }
}

module.exports = HelloAsyncPlugin;

Example

일단 webpack compiler와 각각의 개별적인 compilations를 이해 할 수 있게 되면, 엔진 자체로 할 수 있는 가능성이 무궁무진해집니다. 기존 파일을 다시 포맷하거나 파생 파일을 만들거나 완전히 새로운 애셋을 만들 수 있습니다.

새로운 빌드 파일인 assets.md를 생성하는 예제를 작성해봅시다. 내용은 빌드에 있는 모든 애셋 파일을 나열합니다. 이 플러그인은 다음과 같습니다.

class FileListPlugin {
  static defaultOptions = {
    outputFile: 'assets.md',
  };

  // 어떤 옵션이 플러그인의 생성자에 전달될 때,
  // (이는 플러그인의 public API입니다.)
  constructor(options = {}) {
    // 기본 옵션에 대해 사용자 지정 옵션을 적용하고
    // 병합된 옵션을 플러그인 메소드에 추가로 사용할 수 있게 합니다.
    // 여기서 모든 옵션을 확인해야 합니다.
    this.options = { ...FileListPlugin.defaultOptions, ...options };
  }

  apply(compiler) {
    const pluginName = FileListPlugin.name;

    // webpack 모듈 인스턴스는 컴파일러 객체로부터 접근할 수 있으며,
    // 이는 사용되는 모듈의 정확한 버전을 보장합니다.
    // (webpack 또는 직접적으로 어떤 심볼을 require/import 하지 말아야 합니다.)
    const { webpack } = compiler;

    // Compilation 객체는 몇 가지 유용한 상수에 대한 참조를 제공합니다.
    const { Compilation } = webpack;

    // Rawsource는 compilation에서 애셋 소스를 나타내는데
    // 사용해야 하는 "sources" 클래스 중 하나입니다.
    const { RawSource } = webpack.sources;

    // 이전 단계에서 compilation 프로세스를 추가로 탭하기 위해서는
    // "thisCompilation" 훅을 탭해야합니다.
    compiler.hooks.thisCompilation.tap(pluginName, (compilation) => {
      // 특정 단계에서 애셋 처리 파이프라인으로 탭합니다.
      compilation.hooks.processAssets.tap(
        {
          name: pluginName,

          // 이후 애셋 처리 단계 중 하나를 사용하여
          // 모든 애셋이 이미 다른 플러그인에 의해 compliation에 추가되었는지 확인합니다.
          stage: Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE,
        },
        (assets) => {
          // "assets"는 compilation의 모든 애셋을 포함하는 객체이고,
          // 객체의 key는 애셋의 경로 이름입니다.
          // 그리고 values 파일 소스입니다.

          // 모든 애셋을 거쳐 반복하고
          // 마크다운 파일로 내용을 생성합니다.
          const content =
            '# In this build:\n\n' +
            Object.keys(assets)
              .map((filename) => `- ${filename}`)
              .join('\n');

          // 출력 디렉터리 webpack에 의해 자동으로 생성되도록
          // compilation에 새로운 애셋을 추가합니다.
          compilation.emitAsset(
            this.options.outputFile,
            new RawSource(content)
          );
        }
      );
    });
  }
}

module.exports = { FileListPlugin };

webpack.config.js

const { FileListPlugin } = require('./file-list-plugin.js');

// 플러그인에 webpack 설정을 사용합니다.
module.exports = {
  // …

  plugins: [
    // 기본 옵션을 사용하여 플러그인을 추가합니다.
    new FileListPlugin(),

    // 또는

    // 지원되는 옵션을 전달하도록 선택할 수 있습니다.
    new FileListPlugin({
      outputFile: 'my-assets.md',
    }),
  ],
};

이렇게 하면 다음과 같은 이름을 가진 마크다운 파일이 생성됩니다.

# In this build:

- main.css
- main.js
- index.html

Different Plugin Shapes

플러그인은 탭 하는 이벤트 훅에 따라 타입으로 분류될 수 있습니다. 모든 이벤트 훅은 동기 또는 비동기 waterfall 또는 병렬 훅으로 사전에 정의되어 있고 훅은 내부적으로 call/callAsync 메소드를 사용하여 호출됩니다. 지원되거나 탭이 된 훅의 목록은 일반적으로 this.hooks 프로퍼티에 명시되어 있습니다.

예시는 다음과 같습니다.

this.hooks = {
  shouldEmit: new SyncBailHook(['compilation']),
};

이것은 SyncBailHook 타입의 훅인 shouldEmit만이 지원되는 훅이고 shouldEmit 훅에 탭 되는 플러그인에 전달되는 유일한 파라미터는 compilation입니다.

지원되는 다양한 훅의 타입은 다음과 같습니다.

Synchronous Hooks

  • SyncHook

    • new SyncHook([params])로 정의됩니다.
    • tap 메소드를 사용하여 탭 됩니다.
    • call(...params) 메소드를 사용하여 호출됩니다.
  • Bail Hooks

    • SyncBailHook[params]로 정의됩니다.
    • tap 메소드를 사용하여 탭 됩니다.
    • call(...params) 메소드를 사용하여 호출됩니다.

    Bail Hook 타입의 훅들은, 각각의 callback 플러그인이 특정한 args를 사용하여 차례로 호출됩니다. 만약 플러그인에 의해 정의되지 않은 값을 제외하고 값이 반환된다면 훅에 의해 값이 반환되고 추가 플러그인 callback은 호출되지 않습니다. 많은 유용한 optimizeChunks, optimizeChunkModules와 같은 이벤트는 SyncBailHooks입니다.

  • Waterfall Hooks

    • SyncWaterfallHook[params]로 정의됩니다.
    • tap 메소드를 사용하여 탭 됩니다.
    • call(...params) 메소드를 사용하여 호출됩니다.

    여기서 각각 플러그인은 이전 플러그인의 반환 값으로부터 인자들을 차례로 호출합니다. 플러그인은 실행 순서를 반드시 고려해야합니다. 실행된 이전의 플러그인으로부터 인자들을 반드시 허용해야합니다. 첫 번째 플러그인의 값은 init입니다. 따라서 waterfall hooks에는 최소 1개의 parameter를 제공해야 합니다. 이 패턴은 ModuleTemplate, ChunkTemplate 등과 같은 webpack 템플릿과 관련된 탭 될 수 있는 인스턴스에서 사용됩니다.

Asynchronous Hooks

  • Async Series Hook

    • AsyncSeriesHook[params]로 정의됩니다.
    • tap/tapAsync/tapPromise 메소드를 사용하여 탭 됩니다.
    • callAsync(...params) 메소드를 사용하여 호출됩니다.

    플러그인 핸들러 함수는 (err?: Error) -> void 서명이 있는 callback 함수와 모든 인자들이 호출됩니다. 핸들러 함수는 등록된 순서대로 호출 됩니다. callback은 모든 핸들러가 호출되고 난 뒤 호출됩니다. Async Series Hook은 또한 emit, run과 같은 이벤트에 흔히 사용되는 패턴입니다.

  • Async waterfall 플러그인은 waterfall 방식으로 비동기식으로 적용될 것입니다.

    • AsyncWaterfallHook[params]로 정의됩니다.
    • tap/tapAsync/tapPromise 메소드를 사용하여 탭 됩니다.
    • callAsync(...params) 메소드를 사용하여 호출됩니다.

    플러그인 핸들러 함수는 (err: Error, nextValue: any) -> void. 서명이 있는 callback 함수와 현재 값으로 호출됩니다. nextValue가 호출되면 다음 핸들러의 현재 값이 됩니다. 첫 번째 핸들러의 현재 값은 init입니다. 모든 핸들러가 적용된 후 callback은 마지막 값으로 호출됩니다. 만약 어떤 핸들러가 err 값을 전달하면 callback은 오류가 호출되고 더이상 핸들러는 호출되지 않습니다. 이 플러그인 패턴은 before-resolveafter-resolve와 같은 이벤트에서 사용할 수 있습니다.

  • Async Series Bail

    • AsyncSeriesBailHook[params]로 정의됩니다.
    • tap/tapAsync/tapPromise 메소드를 사용하여 탭 됩니다.
    • callAsync(...params) 메소드를 사용하여 호출됩니다.
  • Async Parallel

    • AsyncParallelHook[params]로 정의됩니다.
    • tap/tapAsync/tapPromise 메소드를 사용하여 탭 됩니다.
    • callAsync(...params) 메소드를 사용하여 호출됩니다.

Configuration defaults

플러그인의 기본값이 적용된 후 webpack은 설정의 기본값을 적용합니다. 이를 통해 플러그인은 고유의 기본값을 제공하고 사전에 플러그인의 설정을 만드는 방법을 제공합니다.

Working Groups

webpack Working Groups

webpack Working Groups are autonomous projects created by the Technical Steering Committee (TSC).

Working Groups can be formed at any time but must be ratified by the TSC. Once formed the work defined in the Working Group charter is the responsibility of the WG rather than the TSC.

It is important that Working Groups are not formed prematurely. Working Groups are not formed to begin a set of tasks but instead are formed once that work is already underway and the contributors think it would benefit from being done as an autonomous project.

If the work defined in a Working Group's charter is complete, the charter should be revoked.

A Working Group's charter can be revoked either by consent of the Working Group's members or by a TSC vote. Once revoked, any future work that arises becomes the responsibility of the TSC.

Joining a WG

To find out how to join a working group, consult the [GOVERNANCE.md][] in the working group's repository.

Starting a Working Group

A Working Group is established by first defining a charter that can be ratified by the TSC. A charter is a statement of purpose and a list of responsibilities. When requesting that a working group be chartered, it is also necessary to provide a list of initial membership.

A working group needs 3 initial members. These should be individuals already undertaking the work described in the charter.

The list of responsibilities should be specific. Once established, these responsibilities are no longer governed by the TSC and therefore should not be broad or subjective. The only recourse the TSC has over the working group is to revoke the entire charter.

If the responsibilities described in the charter are currently undertaken by another working group then the charter will additionally have to be ratified by that working group.

You can submit the working group charter for ratification by sending a pull request to this document to add the charter it to the list of current Working Groups. Once ratified, the list of members should be maintained in the Working Group's README.

Bootstrap Governance

Once the TSC ratifies a charter, the working group inherits the following documentation for governance, contribution, conduct and an MIT LICENSE. The working group is free to change these documents through their own governance process, hence the term "bootstrap."

### *[insert WG name]* Working Group

The webpack *[insert WG name]* is governed by a Working Group (WG)
that is responsible for high-level guidance of the project.

The WG has final authority over this project including:

* Technical direction
* Project governance and process (including this policy)
* Contribution policy
* GitHub repository hosting
* Conduct guidelines
* Maintaining the list of additional Collaborators

For the current list of WG members, see the project
[README.md](https://github.com/webpack/webpack/blob/main/README.md#current-project-members).

### Collaborators

The *[insert WG name]* GitHub repository is
maintained by the WG and additional Collaborators who are added by the
WG on an ongoing basis.

Individuals making significant and valuable contributions are made
Collaborators and given commit-access to the project. These
individuals are identified by the WG and their addition as
Collaborators is discussed during the weekly WG meeting.

Modifications of the contents of the *[insert WG repo]* repository are made on
a collaborative basis. Anybody with a GitHub account may propose a
modification via pull request and it will be considered by the project
Collaborators. All pull requests must be reviewed and accepted by a
Collaborator with sufficient expertise who is able to take full
responsibility for the change. In the case of pull requests proposed
by an existing Collaborator, an additional Collaborator is required
for sign-off. Consensus should be sought if additional Collaborators
participate and there is disagreement around a particular
modification. See _Consensus Seeking Process_ below for further detail
on the consensus model used for governance.

For the current list of Collaborators, see the project
[README.md](https://github.com/webpack/webpack/blob/main/README.md#current-project-members).

### WG Membership

WG seats are not time-limited.  There is no fixed size of the WG.
However, the expected target is between 6 and 12, to ensure adequate
coverage of important areas of expertise, balanced with the ability to
make decisions efficiently.

There is no specific set of requirements or qualifications for WG
membership beyond these rules.

The WG may add additional members to the WG by unanimous consensus.

A WG member may be removed from the WG by voluntary resignation, or by
unanimous consensus of all other WG members.

Changes to WG membership should be posted in the agenda, and may be
suggested as any other agenda item (see "WG Meetings" below).

If an addition or removal is proposed during a meeting, and the full
WG is not in attendance to participate, then the addition or removal
is added to the agenda for the subsequent meeting.  This is to ensure
that all members are given the opportunity to participate in all
membership decisions.  If a WG member is unable to attend a meeting
where a planned membership decision is being made, then their consent
is assumed.

No more than 1/3 of the WG members may be affiliated with the same
employer.  If removal or resignation of a WG member, or a change of
employment by a WG member, creates a situation where more than 1/3 of
the WG membership shares an employer, then the situation must be
immediately remedied by the resignation or removal of one or more WG
members affiliated with the over-represented employer(s).

### Consensus Seeking Process

The WG follows a [Consensus Seeking][] decision-making model.

If an agenda item cannot reach a consensus a WG member can call for
either a closing vote or a vote to table the issue to the next
meeting. The call for a vote must be seconded by a majority of the WG
or else the discussion will continue. Simple majority wins.

Note that changes to WG membership require unanimous consensus. See
"WG Membership" above.

<a id="developers-certificate-of-origin"></a>
## Developer's Certificate of Origin 1.1

Use of a CLA or DCO is mandatory for all all OpenJS Foundation projects.
The webpack project has chosen to use the DCO 1.1

By making a contribution to this project, I certify that:

* (a) The contribution was created in whole or in part by me and I
  have the right to submit it under the open source license
  indicated in the file; or

* (b) The contribution is based upon previous work that, to the best
  of my knowledge, is covered under an appropriate open source
  license and I have the right under that license to submit that
  work with modifications, whether created in whole or in part
  by me, under the same open source license (unless I am
  permitted to submit under a different license), as indicated
  in the file; or

* (c) The contribution was provided directly to me by some other
  person who certified (a), (b) or (c) and I have not modified
  it.

* (d) I understand and agree that this project and the contribution
  are public and that a record of the contribution (including all
  personal information I submit with it, including my sign-off) is
  maintained indefinitely and may be redistributed consistent with
  this project or the open source license(s) involved.

### Moderation Policy

The [webpack Moderation Policy] applies to this WG.

### Code of Conduct

The [webpack Code of Conduct][] applies to this WG.

[webpack Code of Conduct]: https://github.com/webpack/webpack/blob/main/CODE_OF_CONDUCT.md
[webpack Moderation Policy]: https://github.com/webpack/governance/blob/main/MODERATION_POLICY.md
[Consensus Seeking]: https://en.wikipedia.org/wiki/Consensus-seeking_decision-making

Current Working Groups

Core

The Core Working Group is responsible for the development and maintenance of the webpack bundler and its technical direction.

Responsibilities include:

  • Maintaining the core of the webpack bundler
  • Reviewing and merging pull requests
  • Managing releases and versioning
  • Ensuring code quality and consistency
  • Addressing issues and bugs reported by the community
  • Developing new features and enhancements
  • Writing and maintaining documentation
  • Coordinating with other working groups and the TSC
  • Ensuring compliance with the project's code of conduct and governance policies

This document is an adaption of the Node.js project Working Groups Charter

Plugin Patterns

플러그인은 webpack 빌드 시스템 내에서 커스터마이징을 수행할 수 있는 무한한 기회를 제공합니다. 이를 통해 커스텀 애셋 유형을 생성하고, 고유한 빌드 수정을 수행할 수 있게 하며, 심지어 미들웨어를 사용하는 동안 webpack 런타임을 향상시킬 수 있습니다. 다음은 플러그인을 작성할 때 유용하게 쓰이는 webpack의 몇 가지 기능입니다.

Exploring assets, chunks, modules, and dependencies

컴파일이 완료된 후에는, 컴파일 내의 모든 구조를 확인할 수 있습니다.

class MyPlugin {
  apply(compiler) {
    compiler.hooks.emit.tapAsync('MyPlugin', (compilation, callback) => {
      // 각 청크(빌드 출력)를 탐색합니다.
      compilation.chunks.forEach((chunk) => {
        // 청크(빌드된 입력) 내의 각 모듈을 탐색합니다.
        chunk.getModules().forEach((module) => {
          // 모듈에 포함된 각 소스 파일 경로를 탐색합니다.
          module.buildInfo &&
            module.buildInfo.fileDependencies &&
            module.buildInfo.fileDependencies.forEach((filepath) => {
              // 이제 소스 구조에 대해 많은 것을 배웠습니다...
            });
        });

        //  청크에 의해 생성된 각 애셋 파일 이름을 탐색합니다.
        chunk.files.forEach((filename) => {
          // 청크에 의해 생성된 각 파일의 애셋 소스를 가져옵니다.
          var source = compilation.assets[filename].source();
        });
      });

      callback();
    });
  }
}
module.exports = MyPlugin;
  • compilation.modules: 컴파일 결과물의 모듈(빌드된 입력) 집합입니다. 각 모듈은 소스 라이브러리의 원시 파일의 빌드를 관리합니다.
  • module.fileDependencies: 모듈에 포함된 소스 파일 경로의 배열입니다. 이것은 자바스크립트 파일 자체(예: index.js)와 필요한 모든 의존성 애셋 파일들(스타일 시트, 이미지 등)을 포함합니다. 의존성을 검토하는 것은 어떤 소스 파일이 모듈에 속하는지 파악하는데 유용합니다.
  • compilation.chunks: 컴파일의 청크 세트(빌드 출력)입니다. 각 청크는 최종 렌더링된 애셋의 구성을 관리합니다.
  • chunk.getModules(): 청크에 포함된 모듈의 배열입니다. 각 모듈의 의존성을 통해 어떤 원시 소스 파일이 청크에 공급되는지 확인할 수 있습니다.
  • chunk.files: 청크에 의해 생성된 출력 파일 이름의 집합입니다. compilation.assets 테이블에서 이러한 애셋 소스를 액세스할 수 있습니다.

Monitoring the watch graph

webpack 미들웨어를 실행하는 동안, 각 컴파일 결과물은 fileDependencies Set (감시되고 있는 파일) 그리고 된 파일 경로를 타임스탬프에 매핑하는 fileTimestamps Map 을 포함합니다. 다음은 컴파일 결과물 내에서 변경된 파일을 감지하는데 매우 유용합니다.

class MyPlugin {
  constructor() {
    this.startTime = Date.now();
    this.prevTimestamps = new Map();
  }
  apply(compiler) {
    compiler.hooks.emit.tapAsync('MyPlugin', (compilation, callback) => {
      const changedFiles = Array.from(compilation.fileTimestamps.keys()).filter(
        (watchfile) => {
          return (
            (this.prevTimestamps.get(watchfile) || this.startTime) <
            (compilation.fileTimestamps.get(watchfile) || Infinity)
          );
        }
      );

      this.prevTimestamps = compilation.fileTimestamps;
      callback();
    });
  }
}

module.exports = MyPlugin;

파일이 변경될 때 컴파일 트리거를 수신하도록 감시 그래프에 새로운 파일 경로를 제공할 수도 있습니다. 유효한 파일 경로를 compilation.fileDependencies Set 에 더하여 감시된 파일에 추가합니다.

Changed chunks

감시 그래프와 유사하게, 해시를 추적하여 컴파일 결과물 내에서 변경된 청크(또는 모듈)를 모니터링할 수 있습니다.

class MyPlugin {
  constructor() {
    this.chunkVersions = {};
  }
  apply(compiler) {
    compiler.hooks.emit.tapAsync('MyPlugin', (compilation, callback) => {
      var changedChunks = compilation.chunks.filter((chunk) => {
        var oldVersion = this.chunkVersions[chunk.name];
        this.chunkVersions[chunk.name] = chunk.hash;
        return chunk.hash !== oldVersion;
      });
      callback();
    });
  }
}

module.exports = MyPlugin;

Release Process

webpack 배포를 위한 릴리스 프로세스는 실제로 매우 간단합니다. 다음 단계를 읽으면, 수행 방법을 명확하게 이해할 수 있습니다.

Pull Requests

pull requests를 main브랜치로 병합할 때, Create Merge Commit 옵션을 선택합니다.

Releasing

npm version patch && git push --follow-tags && npm publish
npm version minor && git push --follow-tags && npm publish
npm version major && git push --follow-tags && npm publish

그러면 패키지 버전이 증가되고, 변경 내용이 커밋되며, 로컬 태그를 잘라내고, github에 푸시 후 npm 패키지를 배포합니다.

그런 다음 github 릴리스 페이지로 이동하여 새 태그에 대한 변경 로그를 작성합니다.

Debugging

코어 저장소에 기여할 때나, 로더 또는 플러그인을 작성할 때, 아니면 복잡한 프로젝트를 작업할 때도 디버깅 도구가 워크 플로에서 중심이 될 수 있습니다. 규모가 큰 프로젝트에서의 느린 성능이나 도움이 되지 않는 트레이스백이 문제라면, 다음의 유틸리티를 사용하여 문제를 보다 수월하게 파악할 수 있습니다.

Stats

이 데이터를 수동으로 조사하거나, 도구를 사용하여 데이터를 처리할 때도 stats 데이터는 빌드 이슈 디버깅에 매우 유용할 수 있습니다. 이 내용을 설명하는 페이지가 있으므로 여기서 자세히 설명하지는 않지만, 다음 정보를 찾는 데 사용할 수 있습니다.

  • 모든 모듈의 내용.
  • 모든 청크에 포함된 모듈.
  • 모듈 별 컴파일 및 통계 분석.
  • 빌드 오류 및 경고.
  • 모듈 간의 관계.
  • 그리고 더 많은 것들..

또한 공식 분석 도구다양한 도구가 이 데이터를 분석하고 여러 방법으로 시각화합니다.

DevTools

console 문은 간단한 시나리오에서는 잘 작동하지만 때로는 더 강력한 솔루션이 필요합니다. 대부분의 프런트엔드 개발자가 이미 알고 있듯이 Chrome DevTools는 웹 애플리케이션을 디버깅할 때 생명의 은인 같은 역할을 합니다. 하지만 거기서 멈추지 않고 더 나아갈 수 있습니다. Node v6.3.0+부터 개발자는 내장된 --inspect 플래그를 사용하여 DevTools에서 Node 프로그램을 디버깅할 수 있습니다.

node --inspect로 webpack을 호출하여 시작합니다.

npm scripts(예를 들어 npm run build)를 실행할 수 없으므로, 전체 node_modules 경로를 지정해야 합니다.

node --inspect ./node_modules/webpack/bin/webpack.js

이는 다음과 같이 출력될 것입니다.

Debugger listening on ws://127.0.0.1:9229/c624201a-250f-416e-a018-300bbec7be2c
For help see https://nodejs.org/en/docs/inspector

이제 브라우저에서 chrome://inspect로 이동하면 Remote Target 헤더 내에 검사 한 활성 스크립트가 표시됩니다. 각 스크립트 하단의 "inspect" 링크를 클릭하여 전용 디버거를 열거나 Open dedicated DevTools for Node 링크를 클릭하여 자동으로 연결되는 세션을 시작할 수 있습니다. 매번 DevTools 탭을 자동으로 여는 편리한 Chrome 플러그인인 NiM 확장 프로그램도 확인해 보세요. 스크립트를 --inspect할 때마다 DevTools 탭을 자동으로 실행하는 유용한 크롬 플러그인입니다.

스크립트의 첫 번째 문에서 중단하는 --inspect-brk 플래그 사용을 추천합니다. 이를 통해 소스를 확인하여 중단점을 설정하고, 원하는 대로 빌드를 시작 또는 중지할 수 있습니다. 또한 여전히 스크립트에 인수를 전달할 수 있다는 점을 잊지 마세요. 예를 들어 설정 파일이 여러 개인 경우--config webpack.prod.js를 전달하여 디버깅할 설정을 지정할 수 있습니다.

1 Contributor

webpack