Repository: microsoft/redux-micro-frontend
Branch: main
Commit: 5a2d96347f8f
Files: 56
Total size: 112.4 KB
Directory structure:
gitextract_bpdac_6z/
├── .github/
│ ├── ISSUE_TEMPLATE/
│ │ ├── bug_report.md
│ │ └── feature_request.md
│ └── workflows/
│ ├── build-and-publish.yml
│ ├── codeql-analysis.yml
│ └── gated-build.yml
├── .gitignore
├── .npmrc
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.ko.md
├── README.md
├── SECURITY.md
├── SUPPORT.md
├── azure-gated-build.yml
├── index.ts
├── karma.conf.headless.js
├── karma.conf.js
├── package.json
├── sample/
│ ├── counterApp/
│ │ ├── .babelrc
│ │ ├── index.html
│ │ ├── package.json
│ │ ├── src/
│ │ │ ├── appCounter.js
│ │ │ ├── counter.js
│ │ │ ├── index.js
│ │ │ └── store/
│ │ │ ├── counterReducer.js
│ │ │ ├── global.actions.js
│ │ │ └── local.actions.js
│ │ ├── webpack.config.js
│ │ └── webpack.config.mf.js
│ ├── shell/
│ │ ├── index.html
│ │ ├── package.json
│ │ ├── src/
│ │ │ └── index.js
│ │ └── webpack.config.js
│ └── todoApp/
│ ├── .babelrc
│ ├── index.html
│ ├── package.json
│ ├── src/
│ │ ├── addTodo.js
│ │ ├── index.js
│ │ ├── store/
│ │ │ ├── todo.actions.js
│ │ │ └── todoReducer.js
│ │ ├── todo.js
│ │ └── todoList.js
│ ├── webpack.config.js
│ └── webpack.config.mf.js
├── src/
│ ├── actions/
│ │ ├── action.interface.ts
│ │ └── index.ts
│ ├── common/
│ │ ├── abstract.logger.ts
│ │ ├── console.logger.ts
│ │ └── interfaces/
│ │ ├── global.store.interface.ts
│ │ └── index.ts
│ ├── global.store.ts
│ └── middlewares/
│ └── action.logger.ts
├── test/
│ ├── global.store.tests.ts
│ └── middlewares/
│ └── action.logger.tests.ts
└── tsconfig.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.md
================================================
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
**Smartphone (please complete the following information):**
- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
**Additional context**
Add any other context about the problem here.
================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.md
================================================
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
================================================
FILE: .github/workflows/build-and-publish.yml
================================================
name: Build-and-Publish
on:
workflow_dispatch:
jobs:
build-and-publish:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Install Dependencies
run: npm install
- name: Build
run: npm run build
- name: Test
run: npm run test
- name: Copy Files
run: npm run copyfiles
- name: Change Directory to lib
run: cd lib
- name: Setup Node
uses: actions/setup-node@v2
with:
node-version: '12.x'
registry-url: 'https://registry.npmjs.org'
- name: Publish
run: cd lib && npm publish
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
================================================
FILE: .github/workflows/codeql-analysis.yml
================================================
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"
on:
push:
branches: [ main, Min_Reviewer_Check ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ main ]
schedule:
- cron: '30 18 * * 5'
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
language: [ 'javascript' ]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ]
# Learn more:
# https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed
steps:
- name: Checkout repository
uses: actions/checkout@v2
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
# ℹ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1
================================================
FILE: .github/workflows/gated-build.yml
================================================
# This is a gated build to verify the validity of the code
name: Gated-Build
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Install Dependencies
run: npm install
- name: Build
run: npm run build
- name: Test
run: npm run test
================================================
FILE: .gitignore
================================================
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Build bits
/lib/**/**.*
# Code Coverage
/coverage/**/**.*
# Ignoring dist folders
/sample/counterApp/dist/**.*
/sample/todoApp/dist/**/**.*
/sample/shell/dist/**/**.*
================================================
FILE: .npmrc
================================================
registry:https://registry.npmjs.org/
always-auth=true
package-lock=false
================================================
FILE: CODE_OF_CONDUCT.md
================================================
# Microsoft Open Source Code of Conduct
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
Resources:
- [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/)
- [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)
- Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing
This project welcomes contributions and suggestions. Most contributions require you to
agree to a Contributor License Agreement (CLA) declaring that you have the right to,
and actually do, grant us the rights to use your contribution. For details, visit
https://cla.microsoft.com.
When you submit a pull request, a CLA-bot will automatically determine whether you need
to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the
instructions provided by the bot. You will only need to do this once across all repositories using our CLA.
If you are adding new features please add unit test cases. For the modification of any existing feature
ensure all existing test cases are running.
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)
or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
================================================
FILE: README.ko.md
================================================
# Redux Micro-Frontend
## 더 이상 사용되지 않는 버전에 대한 경고
만약 당신이 1.1.0 버전을 사용하고 있을 경우, 바로 최신 버전으로 업그레이드를 하십시오. 해당 버전은 파이프라인 이슈로 인해 더 이상 사용되지 않습니다.
## 파이프라인 상태
[](https://dev.azure.com/MicrosoftIT/OneITVSO/_build/latest?definitionId=32881&branchName=azure-pipelines)
[](https://github.com/microsoft/redux-micro-frontend/actions/workflows/codeql-analysis.yml)
[](https://github.com/microsoft/redux-micro-frontend/actions/workflows/build-and-publish.yml)

## 개요
이 라이브러리는 Redux를 마이크로 프론트엔드 기반의 아키텍쳐에서 사용하기 위해 만들어졌습니다. 마이크로 프론트엔드는 모노리스 프론트엔드 애플리케이션을 벗어나 다루고 쉽고, 분리된, 또 작은 단위의 어플리케이션을 구현하기 위한 아키텍쳐 패턴입니다. 각 애플리케이션은 독립적이고 자립적인 하나의 유닛이 됩니다. 일반적으로 껍데기(shell) 애플리케이션은 엔드 유저들에게 비슷한 경험을 제공하기 위해 이러한 작은 유닛들에 대한 호스트로 사용되도록 구현됩니다.
`Redux`는 예측가능한 상태 관리를 위해 만들어진 유명한 라이브러리들 중 하나입니다. 하지만, 일반적으로 리덕스를 사용할 때 하나의 store를 두고 하나의 상태 객체를 가지게 됩니다. 이 접근은 모든 마이크로 프론트엔드가 하나의 상태를 공유할 수 있다는 것을 의미합니다. 하지만 마이크로 프론트엔드 기반의 아키텍쳐에서 각 애플리케이션은 해당 스토어에 대해 독립적으로 운영되기 때문에 이러한 요소는 마이크로 프론트엔드 아키텍쳐에서 문제 요소로 작용합니다.
몇몇의 개발자는 마이크로 프론트엔드의 각 애플리케이션의 분리 수준을 제공하기 위해 `combineReducer()`를 사용하기도 합니다. 마이크로 프론트엔드를 구현하기 위해 분리된 리듀서를 작성하고, 이들을 하나의 거대한 리듀서로 통합하기 위해서 말이지요. 이러한 것들이 어느 정도의 문제를 해결할 수는 있지만, 이는 단 하나의 상태 객체가 모든 각각의 앱들에 대해 공유된다는 것을 의미합니다. 이는 충분한 조치가 없을 경우, 각각의 앱들이 뜻하지 않게 다른 상태 객체들을 재정의(override)할 수도 있습니다.
마이크로 프론트엔드 아키텍쳐에서, 각각의 애플리케이션은 다른 앱들의 상태에 접근하여 상태값을 수정해서는 안됩니다. 그럼에도 각각의 앱들은 다른 앱들의 상태를 알아야 할 경우가 있습니다. 애플리케이션 간의 커뮤니케이션을 가능케하는 선에서 그들은 이벤트 또는 액션을 다른 스토어에 전달할 수 있습니다. 나아가, 다른 앱들 사이의 상태 변화를 감지할 수도 있습니다. 이 라이브러리는 각 애플리케이션의 분리와 애플리케이션 간의 커뮤니케이션 두 개의 마이크로 프론트엔드 아키텍쳐 요구사항을 만족시킬 수 있는 라이브러리입니다.
## 개념
`전역 스토어`의 개념은 다양한 `리덕스 스토어`들을 가상으로 병합하기 위해 도입되었습니다. 엄밀히 말하면, `전역 스토어`는 스토어는 아닙니다. 오히려 이는 다양한 독립적인 `리덕스 스토어`들의 집합입니다. 각각의 물리적인 `리덕스 스토어`는 각각의 앱이 사용하는 독립된 스토어를 참조합니다. `전역 스토어`에 접근하는 마이크로 프론트엔드 앱들은 `getState()`, `dispatch()` 그리고 `subscribe()`와 같은 각각의 `리덕스 스토어`에 대한 모든 작업들을 수행할 수 있습니다.
각각의 마이크로 프론트엔드 앱들은 그들만의 `리덕스 스토어`를 가질 수 있습니다. 각각의 앱들은 그들의 `리덕스 스토어`를 만들고 `전역 스토어`에 등록할 수 있습니다. 그 `전역 스토어`는 이러한 개별 리덕스 스토어를 사용하여 다른 모든 스토어의 상태를 조합한 전역 상태(Global State)를 투영합니다. 모든 마이크로 프론트엔드 앱들은 이 `전역 스토어`에 접근할 수 있고, 다른 마이크로 프론트엔드의 상태를 볼 수 있습니다. 하지만 그들을 수정할 수는 없죠. 앱에서 디스패치된 작업은 앱에서 등록된 스토어 내에서 제한되어 있어 다른 스토어에 디스패치되지 않으므로 컴포넌트화 또는 분리가 가능합니다.
### 더 읽어볼 것들
[상태 관리의 기본](https://www.devcompost.com/post/state-management-for-front-end-applications-part-i-what-and-why)
### 전역 액션
전역 액션은 특정 앱이 다른 마이크로 프론트엔드 앱에 의해 등록된 스토어에 액션을 디스패치할 수 있는 개념입니다. 각 마이크로 프론트엔드 앱에는 스토어와 함께 전역 액션 집합을 등록할 수 있는 기능이 있습니다. 이러한 전역 액션 집합은 다른 마이크로 프론트엔드 앱에 의해 해당 마이크로 프론트엔드의 스토어에서 디스패치될 수 있습니다. 따라서 애플리케이션 간의 통신이 가능하게 됩니다.

### 상태 간의 상호 콜백
애플리케이션 간의 커뮤니케이션은 다른 마이크로 프론트엔드의 상태에 대한 변화를 구독하는 것으로부터 이루어집니다. 각각의 마이크로 프론트엔드 앱들은 다른 상태들에 대해 읽기 권한만(read-only) 가지고 있기 때문에, 그들은 상태 변화를 읽기 위해 콜백을 붙일 수 있습니다. 콜백들은 각각 스토어 레벨 또는 전역 레벨로 붙여질 수 있습니다. (전역 레벨 콜백은 어떤 스토어이던 상태 변화가 발생할 경우 콜백을 일으킨다는 것을 의미합니다.)
## 단일 상태 공유의 문제점
- 실수로 다른 앱의 상태를 재정의할 수 있습니다. (중복된 액션들이 여러 앱에 의해 디스패치되는 경우)
- 앱들은 다른 마이크로 프론트엔드들을 알고 있어야 합니다.
- 공유된 미들웨어들. 하나의 스토어만 유지되기 때문에, 모든 마이크로 프론트엔드들이 동일한 미들웨어를 공유해야 합니다. 따라서 어떤 앱은 `redux-saga`를 쓰고, 어떤 앱은 `redux-thunk`를 하는 등의 작업은 할 수 없습니다.
## 설치
```sh
npm install redux-micro-frontend --save
```
## 빠른 적용
### 전역 스토어의 인스턴스 얻기
```javascript
import { GlobalStore } from 'redux-micro-frontend';
...
this.globalStore = GlobalStore.Get();
```
### 스토어를 생성하고 등록하기
```javascript
let appStore = createStore(AppReducer); // 리덕스 스토어
this.globalStore.RegisterStore("App1", appStore);
this.globalStore.RegisterGlobalActions("App1", ["Action-1", "Action-2"]); // 이 액션들은 다른 앱들에 의해 이 스토어에 디스패치될 수 있습니다.
```
### 액션 디스패치하기
```javascript
let action = {
type: 'Action-1',
payload: 'Some data'
}
this.globalStore.DispatchAction("App1", action); // 이는 현재 앱의 스토어뿐만 아니라, 'Action-1'을 전역 액션으로 등록한 다른 스토어로도 액션이 전송됩니다.
```
### 상태 구독하기
```javascript
// 모든 앱들의 상태 변화
this.globalStore.Subscribe("App1", localStateChanged);
// 현재 앱의 상태 변화
this.globalStore.SubscribeToGlobalState("App1", globalStateChanged);
// App2의 상태 변화
this.globalStore.SubscribeToPartnerState("App1", "App2", app2StateChanged);
...
localStateChanged(localState) {
// 새로운 상태에 대한 작업을 수행하세요.
}
globalStateChanged(stateChanged) {
// 전역 상태는 스토어에 등록된 모든 앱들을 위한 분리된 어트리뷰트를 가질 수 있습니다.
let app1State = globalState.App1;
let app2State = globalState.App2;
}
app2StateChanged(app2State) {
// app2의 새로운 상태에 대한 작업을 수행하세요.
}
```
## 샘플 앱
위치: https://github.com/microsoft/redux-micro-frontend/tree/main/sample
샘플 앱을 실행하기 위한 안내서
1. sample/counterApp으로 가서 `npm i`을 실행하세요. 그리고 `npm run start`을 하세요.
2. sample/todoApp으로 가서 `npm i`을 실행하세요. 그리고 `npm run start`을 하세요.
3. sample/shell으로 가서 `npm i`을 실행하세요. 그리고 `npm run start`을 하세요.
4. http://localhost:6001을 여세요.
## 문서
[Github 위키](https://github.com/microsoft/redux-micro-frontend/wiki)
## 부록
- Redux의 기본기를 배우기 위해서는 Redux 공식 문서를 확인하세요. - https://redux.js.org/.
- 마이크로 프론트엔드 아키텍쳐에 대해 더 알고 싶다면, [martinfowler.com](http://martinfowler.com/)에서 만든 [이 아티클](https://martinfowler.com/articles/micro-frontends.html)을 확인하세요.
## Trademarks
이 프로젝트에는 프로젝트, 제품 또는 서비스의 상표 또는 로고가 포함될 수 있습니다. Microsoft 상표 또는 로고의 승인된 사용은 Microsoft의 상표 & 브랜드 지침의 적용을 받으며 반드시 따라야 합니다. 이 프로젝트의 수정된 버전에서 Microsoft 상표 또는 로고를 사용하면 Microsoft의 후원이 혼동되거나 암시되어서는 안 됩니다. 타사 상표 또는 로고는 해당 타사 정책의 적용을 받습니다.
================================================
FILE: README.md
================================================
# Redux Micro-Frontend
[한국어🇰🇷](./README.ko.md)
## Version Deprecation Warning
1.1.0 - If you are using this version, please upgrade to latest immediately. This version has been deprecated due to a pipeline issue.
## Pipeline Status
[](https://dev.azure.com/MicrosoftIT/OneITVSO/_build/latest?definitionId=32881&branchName=azure-pipelines)
[](https://github.com/microsoft/redux-micro-frontend/actions/workflows/codeql-analysis.yml)
[](https://github.com/microsoft/redux-micro-frontend/actions/workflows/build-and-publish.yml)

## Overview
This library can be used for using Redux in a Micro Frontend based architecture. Micro Frontends is an architectural pattern for breaking up a monolith Frontend application into manageable, decoupled and smaller applications. Each application is a self-contained and isolated unit. Generally, a common shell/platform application is used to host these small units to provide a common experience for the end-users.
`Redux` is one of the most popular libraries for predictable state management. However, the general practice in using Redux is to have a single store, thereby having a single state object. This approach would mean that all the Micro Frontends would have a shared state. This is a violation of the Micro Frontend based architecture since each App is supposed to be a self-contained unit having its store.
To provide a level of isolation some developers use `combineReducer()` to write a separate reducer for each Micro Frontend and then combine them into one big reducer. Although it would solve some problems this would still imply that a single state object is shared across all the apps. In the absence of sufficient precautions, apps might accidentally override each other's state.
In a Micro Frontend architecture, an individual application should not be able to modify the state of other apps. However, they should be able to see the state of other apps. Along the same line for enabling cross-application communication, they should also be able to send events/actions to other Stores and also get notified of changes in other apps' state. This library aims to attain that sweet spot between providing isolation and cross-application communication.
## Concept
A concept of `Global Store` is introduced which is a virtual amalgamation of multiple `Redux Stores`. Strictly speaking, the `Global Store` is not an actual store, rather it's a collection of multiple isolated `Redux Stores`. Each physical `Redux Store` here refers to the isolated store that each app uses. Micro frontends having access to the `Global Store` would be able to perform all operations that are allowed on an individual `Redux Store` including `getState()`, `dispatch()` and `subscribe()`.
Each Micro Frontend would have the capability to have its own `Redux Store`. Each app would create and register their `Redux Store` with the `Global Store`. The `Global Store` then uses these individual stores to project a Global State which is a combination of the state from all the other Stores. All the Micro Frontends would have access to the Global Store and would be able to see the state from the other Micro Frontends but won't be able to modify them. Actions dispatched by an app remains confined within the store registered by the app and is not dispatched to the other stores, thereby providing componentization and isolation.
### Read more
- [State Management Basics](https://www.devcompost.com/post/state-management-for-front-end-applications-part-i-what-and-why)
- [State Management in Micro Frontends](https://www.devcompost.com/post/state-management-ii-world-of-micro-frontends)
### Global Actions
A concept of `Global Action` is available which allows other apps to dispatch actions to stores registered by other Micro Frontends. Each Micro Frontend has the capability to register a set of global actions along with the store. These set of global actions can be dispatched in this Micro Frontend's store by other Micro Frontends. This enables cross-application communication.

### Cross-state callbacks
Cross-application communication can also be achieved by subscribing to change notifications in other Micro Frontend's state. Since each micro-frontend has read-only permission to other states, they can also attach callbacks for listening to state changes. The callbacks can be attached either at an individual store level or at a global level (this would mean that state change in any store would invoke the callback).
## Problems of a single shared state
- Accidental override of state of other apps (in case duplicate actions are dispatched by multiple apps)
- Apps would have to be aware of other Micro Frontends
- Shared middlewares. Since only a single store is maintained, all the Micro Frontends would have to share the same middlewares. So in situations where one app wants to use `redux-saga` and other wants to use `redux-thunk` is not possible.
## Installation
```sh
npm install redux-micro-frontend --save
```
## Quick Guide
### Get an instance of Global Store
```javascript
import { GlobalStore } from 'redux-micro-frontend';
...
this.globalStore = GlobalStore.Get();
```
### Create/Register Store
```javascript
let appStore = createStore(AppReducer); // Redux Store
this.globalStore.RegisterStore("App1", appStore);
this.globalStore.RegisterGlobalActions("App1", ["Action-1", "Action-2"]); // These actions can be dispatched by other apps to this store
```
### Dispatch Action
```javascript
let action = {
type: 'Action-1',
payload: 'Some data'
}
this.globalStore.DispatchAction("App1", action); // This will dispatch the action to current app's store as well other stores who might have registered 'Action-1' as a global action
```
### Subscribe to State
```javascript
// State change in any of the apps
this.globalStore.Subscribe("App1", localStateChanged);
// State change in the current app
this.globalStore.SubscribeToGlobalState("App1", globalStateChanged);
// State change in app2's state
this.globalStore.SubscribeToPartnerState("App1", "App2", app2StateChanged);
...
localStateChanged(localState) {
// Do something with the new state
}
globalStateChanged(stateChanged) {
// The global state has a separate attribute for all the apps registered in the store
let app1State = globalState.App1;
let app2State = globalState.App2;
}
app2StateChanged(app2State) {
// Do something with the new state of app 2
}
```
## Sample App
Location: https://github.com/microsoft/redux-micro-frontend/tree/main/sample
Instruction for running Sample App
1. Go to sample/counterApp and run `npm i` and then `npm run start`
2. Go to sample/todoApp and run `npm i` and then `npm run start`
3. Go to sample/shell and run `npm i` and then `npm run start`
4. Browse http://localhost:6001
## Documentation
[See Github wiki](https://github.com/microsoft/redux-micro-frontend/wiki)
## Appendix
- To learn the basics for Redux check for [official documentation of Redux](https://redux.js.org/) - https://redux.js.org/.
- To know more about [Micro Front-end](https://martinfowler.com/articles/micro-frontends.html) style of architecture check [this article](https://martinfowler.com/articles/micro-frontends.html) from [martinfowler.com](https://martinfowler.com/articles/micro-frontends.html).
## Trademarks
This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft
trademarks or logos is subject to and must follow
[Microsoft's Trademark & Brand Guidelines](https://www.microsoft.com/en-us/legal/intellectualproperty/trademarks/usage/general).
Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship.
Any use of third-party trademarks or logos are subject to those third-party's policies.
================================================
FILE: SECURITY.md
================================================
## Security
Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/).
If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://docs.microsoft.com/en-us/previous-versions/tn-archive/cc751383(v=technet.10)), please report it to us as described below.
## Reporting Security Issues
**Please do not report security vulnerabilities through public GitHub issues.**
Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://msrc.microsoft.com/create-report).
If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://www.microsoft.com/en-us/msrc/pgp-key-msrc).
You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc).
Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue:
* Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.)
* Full paths of source file(s) related to the manifestation of the issue
* The location of the affected source code (tag/branch/commit or direct URL)
* Any special configuration required to reproduce the issue
* Step-by-step instructions to reproduce the issue
* Proof-of-concept or exploit code (if possible)
* Impact of the issue, including how an attacker might exploit the issue
This information will help us triage your report more quickly.
If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://microsoft.com/msrc/bounty) page for more details about our active programs.
## Preferred Languages
We prefer all communications to be in English.
## Policy
Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://www.microsoft.com/en-us/msrc/cvd).
================================================
FILE: SUPPORT.md
================================================
# Support
## How to file issues and get help
This project uses GitHub Issues to track bugs and feature requests. Please search the existing
issues before filing new issues to avoid duplicates. For new issues, file your bug or
feature request as a new Issue.
For help and questions about using this project, please **REPO MAINTAINER: INSERT INSTRUCTIONS HERE
FOR HOW TO ENGAGE REPO OWNERS OR COMMUNITY FOR HELP. COULD BE A STACK OVERFLOW TAG OR OTHER
CHANNEL. WHERE WILL YOU HELP PEOPLE?**.
## Microsoft Support Policy
Support for this **PROJECT or PRODUCT** is limited to the resources listed above.
================================================
FILE: azure-gated-build.yml
================================================
trigger: none
jobs:
- job: BuildLibrary
displayName: Build Library
pool:
vmImage: ubuntu-latest
steps:
- task: NodeTool@0
inputs:
versionSpec: '12.x'
checkLatest: true
- task: Npm@1
displayName: Install Dependencies
inputs:
command: 'install'
- task: Npm@1
displayName: Build Library
inputs:
command: 'custom'
customCommand: 'run build'
- task: Npm@1
displayName: Test
inputs:
command: 'custom'
customCommand: 'run test'
- job: BuildSample
displayName: Build Sample Projects
pool:
vmImage: ubuntu-latest
steps:
- task: NodeTool@0
inputs:
versionSpec: '12.x'
checkLatest: true
- task: Npm@1
displayName: Install Counter App Dependencies
inputs:
command: 'install'
workingDir: 'sample/counterApp'
- task: Npm@1
displayName: Build Counter App
inputs:
command: 'custom'
customCommand: 'run build'
workingDir: 'sample/counterApp'
- task: Npm@1
displayName: Install Todo App Dependencies
inputs:
command: 'install'
workingDir: 'sample/todoApp'
- task: Npm@1
displayName: Build Todo App
inputs:
command: 'custom'
customCommand: 'run build'
workingDir: 'sample/todoApp'
- task: Npm@1
displayName: Install Shell Dependencies
inputs:
command: 'install'
workingDir: 'sample/shell'
- task: Npm@1
displayName: Build Shell
inputs:
command: 'custom'
customCommand: 'run build'
workingDir: 'sample/shell'
================================================
FILE: index.ts
================================================
export * from './src/actions';
export * from './src/global.store';
export * from './src/common/interfaces';
export * from './src/common/abstract.logger';
export * from './src/common/interfaces/global.store.interface';
================================================
FILE: karma.conf.headless.js
================================================
module.exports = function (config) {
config.set({
frameworks: ["jasmine", "karma-typescript"],
files: [
{ pattern: "src/**/*.ts" },
{ pattern: "test/**/*.ts" }
],
preprocessors: {
"src/**/*.ts": ["karma-typescript"],
"test/**/*.ts": "karma-typescript"
},
reporters: ["progress"],
customLaunchers: {
ChromeHeadlessCustom: {
base: 'ChromeHeadless',
flags: ['--no-sandbox', '--disable-gpu']
}
},
browsers: ["ChromeHeadlessCustom"],
karmaTypescriptConfig: {
coverageReporter: {
instrumenterOptions: {
istanbul: { noCompact: true }
}
},
bundlerOptions: {
transforms: [
require("karma-typescript-es6-transform")({
presets: [
["env", {
targets: {
chrome: "60"
}
}]
]
})
]
},
compilerOptions: {
module: "commonjs",
sourceMap: true,
target: "es6",
allowJs: false,
declaration: true,
moduleResolution: "node",
skipLibCheck: true,
lib: ["es2017", "DOM"],
downlevelIteration: true
},
typeRoots: [
"node_modules/@types"
],
exclude: [
"node_modules/**/*"
]
},
singleRun: true,
autoWatch: false,
plugins: ['karma-jasmine', 'karma-chrome-launcher', 'karma-typescript']
});
};
================================================
FILE: karma.conf.js
================================================
module.exports = function (config) {
config.set({
frameworks: ["jasmine", "karma-typescript"],
files: [
{ pattern: "src/**/*.ts" },
{ pattern: "test/**/*.ts" }
],
preprocessors: {
"src/**/*.ts": ["karma-typescript"],
"test/**/*.ts": "karma-typescript"
},
reporters: ["progress", "karma-typescript"],
browsers: ["Chrome"],
karmaTypescriptConfig: {
coverageReporter: {
instrumenterOptions: {
istanbul: { noCompact: true }
}
},
bundlerOptions: {
transforms: [
require("karma-typescript-es6-transform")({
presets: [
["env", {
targets: {
chrome: "60"
}
}]
]
})
]
},
compilerOptions: {
module: "commonjs",
sourceMap: true,
target: "es6",
allowJs: false,
declaration: true,
moduleResolution: "node",
skipLibCheck: true,
lib: ["es2017", "DOM"],
downlevelIteration: true
},
typeRoots: [
"node_modules/@types"
],
exclude: [
"node_modules/**/*"
]
},
plugins: ['karma-jasmine', 'karma-chrome-launcher', 'karma-typescript']
});
};
================================================
FILE: package.json
================================================
{
"name": "redux-micro-frontend",
"version": "1.3.0",
"license": "MIT",
"description": "This is a library for using Redux to managing state for self-contained apps in a Micro-Frontend architecture. Each self-contained isolated app can have its own isolated and decoupled Redux store. The componentized stores interact with a global store for enabling cross-application communication.",
"author": {
"name": "Pratik Bhattacharya",
"email": "pratikb@microsoft.com",
"url": "https://www.devcompost.com/"
},
"homepage": "https://github.com/microsoft/redux-micro-frontend",
"keywords": [
"redux",
"micro frontend",
"microfrontend",
"microfrontends",
"micro frontends",
"state",
"statemanagement"
],
"bugs": {
"url": "https://github.com/microsoft/redux-micro-frontend/issues",
"email": "pratikb@microsoft.com"
},
"repository": {
"type": "git",
"url": "https://github.com/microsoft/redux-micro-frontend"
},
"scripts": {
"build": "tsc",
"test-chrome": "karma start karma.conf.js",
"test": "karma start karma.conf.headless.js",
"release:pre": "npm run build && npm version prerelease && npm run copyfiles:publish-beta",
"release:patch": "npm run build && npm version patch && npm run copyfiles:publish",
"release:minor": "npm run build && npm version minor && npm run copyfiles:publish",
"release:major": "npm run build && npm version major && npm run copyfiles:publish",
"copyfiles": "npm run copy:packagejson && npm run copy:npmrc",
"copyfiles:publish": "npm run copy:packagejson && npm run copy:npmrc && cd lib && npm publish",
"copyfiles:publish-beta": "npm run copy:packagejson && npm run copy:npmrc && cd lib && npm publish --tag beta",
"copy:packagejson": "cpr package.json lib/package.json -o",
"copy:npmrc": "cpr .npmrc lib/.npmrc -o",
"clean": "rimraf node_modules",
"rebuild": "npm run clean && npm i && npm build"
},
"private": false,
"dependencies": {
"flatted": "^2.0.2",
"redux": "^4.0.5",
"redux-devtools-extension": "^2.13.8"
},
"devDependencies": {
"@types/jasmine": "^3.5.14",
"cpr": "^3.0.1",
"jasmine": "^3.6.2",
"karma": "^6.3.4",
"karma-chrome-launcher": "^3.1.0",
"karma-coverage": "^2.0.3",
"karma-jasmine": "^3.3.1",
"karma-typescript": "^5.5.1",
"karma-typescript-es6-transform": "^4.1.1",
"puppeteer": "^5.5.0",
"rimraf": "^3.0.2",
"typescript": "^3.5.3"
}
}
================================================
FILE: sample/counterApp/.babelrc
================================================
{
"presets": [
"@babel/preset-react"
]
}
================================================
FILE: sample/counterApp/index.html
================================================