├── .bookignore ├── .editorconfig ├── .eslintrc ├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── PULL_REQUEST_TEMPLATE └── workflows │ ├── pr.yml │ └── release.yml ├── .gitignore ├── .prettierignore ├── .prettierrc ├── .releaserc ├── .vscode └── extensions.json ├── README.md ├── SUMMARY.md ├── apps └── sandbox │ ├── .eslintrc │ ├── browserslist │ ├── jest.config.js │ ├── src │ ├── app │ │ └── app.element.ts │ ├── assets │ │ └── .gitkeep │ ├── environments │ │ ├── environment.prod.ts │ │ └── environment.ts │ ├── favicon.ico │ ├── index.html │ ├── main.ts │ ├── polyfills.ts │ ├── styles.scss │ └── test-setup.ts │ ├── tsconfig.app.json │ ├── tsconfig.json │ ├── tsconfig.spec.json │ └── webpack.config.js ├── code_of_conduct.md ├── contributing.md ├── docs ├── README.md ├── how_does_it_work.md ├── installation_and_configuration.md ├── the_plugin.md └── tree_shaing.md ├── jest.config.js ├── libs └── shared-library-webpack-plugin │ ├── .eslintrc │ ├── .gitignore │ ├── __tests__ │ ├── 1.js │ ├── 2.js │ └── 3.js │ ├── jest.config.js │ ├── package.json │ ├── src │ ├── index.ts │ └── lib │ │ ├── __snapshots__ │ │ └── shared-library-webpack-plugin.spec.ts.snap │ │ ├── shared-library-webpack-plugin.spec.ts │ │ ├── shared-library-webpack-plugin.ts │ │ ├── utils.spec.ts │ │ └── utils.ts │ ├── tsconfig.json │ ├── tsconfig.lib.json │ └── tsconfig.spec.json ├── license.md ├── nx.json ├── package-lock.json ├── package.json ├── tools ├── schematics │ └── .gitkeep └── tsconfig.tools.json ├── tsconfig.json └── workspace.json /.bookignore: -------------------------------------------------------------------------------- 1 | .github/* -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see http://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.md] 12 | max_line_length = off 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "root": true, 3 | "parser": "@typescript-eslint/parser", 4 | "parserOptions": { 5 | "ecmaVersion": 2018, 6 | "sourceType": "module", 7 | "project": "./tsconfig.json" 8 | }, 9 | "ignorePatterns": ["**/*"], 10 | "plugins": ["@typescript-eslint", "@nrwl/nx"], 11 | "extends": [ 12 | "eslint:recommended", 13 | "plugin:@typescript-eslint/eslint-recommended", 14 | "plugin:@typescript-eslint/recommended", 15 | "prettier", 16 | "prettier/@typescript-eslint" 17 | ], 18 | "rules": { 19 | "@typescript-eslint/explicit-member-accessibility": "off", 20 | "@typescript-eslint/explicit-function-return-type": "off", 21 | "@typescript-eslint/no-parameter-properties": "off", 22 | "@nrwl/nx/enforce-module-boundaries": [ 23 | "error", 24 | { 25 | "enforceBuildableLibDependency": true, 26 | "allow": [], 27 | "depConstraints": [ 28 | { "sourceTag": "*", "onlyDependOnLibsWithTags": ["*"] } 29 | ] 30 | } 31 | ] 32 | }, 33 | "overrides": [ 34 | { 35 | "files": ["*.tsx"], 36 | "rules": { 37 | "@typescript-eslint/no-unused-vars": "off" 38 | } 39 | } 40 | ] 41 | } 42 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # ================================================================================== 2 | # ================================================================================== 3 | # shared-library-webpack-plugin codeowners 4 | # ================================================================================== 5 | # ================================================================================== 6 | # 7 | # Configuration of code ownership and review approvals for the angular/angular repo. 8 | # 9 | # More info: https://help.github.com/articles/about-codeowners/ 10 | # 11 | 12 | * @IKatsuba 13 | # will be requested for review when someone opens a pull request -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '[bug]' 5 | labels: bug 6 | assignees: '' 7 | --- 8 | 9 | **Describe the bug** 10 | A clear and concise description of what the bug is. 11 | 12 | **To Reproduce** 13 | Steps to reproduce the behavior: 14 | 15 | 1. Go to '...' 16 | 2. ... 17 | 18 | **Expected behavior** 19 | A clear and concise description of what you expected to happen. 20 | 21 | **Screenshots** 22 | If applicable, add screenshots to help explain your problem. 23 | 24 | **Desktop (please complete the following information):** 25 | 26 | - OS: [e.g. macOS] 27 | - Browser [e.g. chrome, safari] 28 | - Version [e.g. 22] 29 | 30 | **Additional context** 31 | Add any other context about the problem here. 32 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: enhancement 6 | assignees: '' 7 | --- 8 | 9 | **Is your feature request related to a problem? Please describe.** 10 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 11 | 12 | **Describe the solution you'd like** 13 | A clear and concise description of what you want to happen. 14 | 15 | **Describe alternatives you've considered** 16 | A clear and concise description of any alternative solutions or features you've considered. 17 | 18 | **Additional context** 19 | Add any other context or screenshots about the feature request here. 20 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE: -------------------------------------------------------------------------------- 1 | ## PR Checklist 2 | Please check if your PR fulfills the following requirements: 3 | 4 | - [ ] The commit message follows [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0-beta.4/) 5 | - [ ] Tests for the changes have been added (for bug fixes / features) 6 | - [ ] Docs have been added / updated (for bug fixes / features) 7 | 8 | 9 | ## PR Type 10 | What kind of change does this PR introduce? 11 | 12 | 13 | 14 | - [ ] Bugfix 15 | - [ ] Feature 16 | - [ ] Refactoring (no functional changes, no api changes) 17 | - [ ] Other... Please describe: 18 | 19 | 20 | ## What is the current behavior? 21 | 22 | 23 | Issue Number: N/A 24 | 25 | 26 | ## What is the new behavior? 27 | 28 | 29 | ## Does this PR introduce a breaking change? 30 | 31 | - [ ] Yes 32 | - [ ] No 33 | 34 | 35 | 36 | 37 | 38 | ## Other information 39 | -------------------------------------------------------------------------------- /.github/workflows/pr.yml: -------------------------------------------------------------------------------- 1 | name: Pull Request 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - master 7 | - next 8 | - beta 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v1 15 | - name: Use Node.js 12.x 16 | uses: actions/setup-node@v1 17 | with: 18 | node-version: 12.x 19 | - name: Build 20 | run: | 21 | npm ci 22 | npm run build 23 | env: 24 | CI: true 25 | lint: 26 | runs-on: ubuntu-latest 27 | steps: 28 | - uses: actions/checkout@v1 29 | - name: Use Node.js 12.x 30 | uses: actions/setup-node@v1 31 | with: 32 | node-version: 12.x 33 | - name: Lint 34 | run: | 35 | npm ci 36 | npm run lint 37 | env: 38 | CI: true 39 | test: 40 | runs-on: ubuntu-latest 41 | steps: 42 | - uses: actions/checkout@v1 43 | - name: Use Node.js 12.x 44 | uses: actions/setup-node@v1 45 | with: 46 | node-version: 12.x 47 | - name: Test 48 | run: | 49 | npm ci 50 | npm test 51 | env: 52 | CI: true 53 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | - next 8 | - beta 9 | 10 | jobs: 11 | release: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v1 15 | - name: Use Node.js 12.x 16 | uses: actions/setup-node@v1 17 | with: 18 | node-version: 12.x 19 | - name: npm install 20 | run: | 21 | npm ci 22 | env: 23 | CI: true 24 | - name: Release 25 | run: | 26 | npm run build 27 | npm run release 28 | env: 29 | CI: true 30 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} 31 | GH_TOKEN: ${{ secrets.GH_TOKEN }} 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /tmp 6 | /out-tsc 7 | 8 | # dependencies 9 | node_modules 10 | 11 | # IDEs and editors 12 | /.idea 13 | .project 14 | .classpath 15 | .c9/ 16 | *.launch 17 | .settings/ 18 | *.sublime-workspace 19 | 20 | # IDE - VSCode 21 | .vscode/* 22 | !.vscode/settings.json 23 | !.vscode/tasks.json 24 | !.vscode/launch.json 25 | !.vscode/extensions.json 26 | 27 | # misc 28 | /.sass-cache 29 | /connect.lock 30 | /coverage 31 | /libpeerconnection.log 32 | npm-debug.log 33 | yarn-error.log 34 | testem.log 35 | /typings 36 | 37 | # System Files 38 | .DS_Store 39 | Thumbs.db 40 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | # Add files here to ignore them from prettier formatting 2 | 3 | /dist 4 | /coverage 5 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true 3 | } 4 | -------------------------------------------------------------------------------- /.releaserc: -------------------------------------------------------------------------------- 1 | { 2 | "plugins": [ 3 | "@semantic-release/commit-analyzer", 4 | "@semantic-release/release-notes-generator", 5 | [ 6 | "@semantic-release/npm", 7 | { 8 | "pkgRoot": "./dist/libs/shared-library-webpack-plugin" 9 | } 10 | ], 11 | "@semantic-release/github" 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "ms-vscode.vscode-typescript-tslint-plugin", 4 | "esbenp.prettier-vscode" 5 | ] 6 | } 7 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SharedLibraryWebpackPlugin 2 | 3 | [![npm](https://img.shields.io/npm/v/@tinkoff/shared-library-webpack-plugin)](https://www.npmjs.com/package/@tinkoff/shared-library-webpack-plugin) [![npm](https://img.shields.io/npm/dm/@tinkoff/shared-library-webpack-plugin)](https://www.npmjs.com/package/@tinkoff/shared-library-webpack-plugin) 4 | 5 | `SharedLibraryWebpackPlugin` is a webpack plugin for sharing libraries between applications. 6 | 7 | ### Motivation 8 | 9 | When the host application loads many micro apps bundled with a webpack, many JavaScript is loaded on a client page. In a perfect world, each app can share its libraries with other apps and meet the requirements: 10 | 11 | 1. Each app stays self-hosted. 12 | 2. Fallbacks for non-loaded packages. 13 | 3. Codesharing in runtime. 14 | 4. Different library versions work individually. 15 | 16 | SharedLibraryWebpackPlugin came to us from a perfect world! 17 | 18 | ### Documentations 19 | 20 | 1. [Installation and configuration](docs/installation_and_configuration.md) 21 | 2. [How is it works?](docs/how_does_it_work.md) 22 | 3. [Sharing and Tree shaking](https://github.com/TinkoffCreditSystems/shared-library-webpack-plugin/tree/15f229429eaf4e9adedbd15b405686a142d0087e/docs/tree_shaking.md) 23 | 4. [The Plugin API](docs/the_plugin.md) 24 | 25 | ### Demo 26 | 27 | There is [a host application with two micro-apps](https://github.com/IKatsuba/shared-library-plugin-demo). All apps are built with Angular. The client page loads 282.8kB of JavaScript \(gzip\) when it opens all pages. 28 | 29 | We add SharedLibraryWebpackPlugin in each app build for sharing all Angular packages and zone.js. 30 | 31 | ```typescript 32 | const { 33 | SharedLibraryWebpackPlugin, 34 | } = require('@tinkoff/shared-library-webpack-plugin'); 35 | 36 | module.exports = { 37 | plugins: [ 38 | new SharedLibraryWebpackPlugin({ 39 | libs: [ 40 | { name: '@angular/core', usedExports: [] }, 41 | { name: '@angular/common', usedExports: [] }, 42 | { name: '@angular/common/http', usedExports: [] }, 43 | { name: '@angular/platform-browser', usedExports: ['DomSanitizer'] }, 44 | { name: '@angular/platform-browser/animations', usedExports: [] }, 45 | { name: '@angular/animations', usedExports: [] }, 46 | { name: '@angular/animations/browser', usedExports: [] }, 47 | 'zone.js/dist/zone', 48 | ], 49 | }), 50 | ], 51 | }; 52 | ``` 53 | 54 | After that, the client page loads 174.6kB of JavaScript! It is 38% less! 55 | 56 | ### [Contributing](contributing.md) 57 | 58 | ### [License](license.md) 59 | 60 | -------------------------------------------------------------------------------- /SUMMARY.md: -------------------------------------------------------------------------------- 1 | # Table of contents 2 | 3 | * [SharedLibraryWebpackPlugin](README.md) 4 | * [Documentation](docs/README.md) 5 | * [Installation and Configuration](docs/installation_and_configuration.md) 6 | * [How does it work?](docs/how_does_it_work.md) 7 | * [Sharing and Tree shaking](docs/tree_shaing.md) 8 | * [The Plugin](docs/the_plugin.md) 9 | * [Contributor Covenant Code of Conduct](code_of_conduct.md) 10 | * [Contributing](contributing.md) 11 | * [License](license.md) 12 | 13 | -------------------------------------------------------------------------------- /apps/sandbox/.eslintrc: -------------------------------------------------------------------------------- 1 | { "extends": "../../.eslintrc", "rules": {}, "ignorePatterns": ["!**/*"] } 2 | -------------------------------------------------------------------------------- /apps/sandbox/browserslist: -------------------------------------------------------------------------------- 1 | # This file is currently used by autoprefixer to adjust CSS to support the below specified browsers 2 | # For additional information regarding the format and rule options, please see: 3 | # https://github.com/browserslist/browserslist#queries 4 | # 5 | # If you need to support different browsers in production, you may tweak the list below. 6 | 7 | > 0.2% 8 | not dead 9 | not op_mini all 10 | -------------------------------------------------------------------------------- /apps/sandbox/jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | name: 'sandbox', 3 | preset: '../../jest.config.js', 4 | coverageDirectory: '../../coverage/apps/sandbox', 5 | }; 6 | -------------------------------------------------------------------------------- /apps/sandbox/src/app/app.element.ts: -------------------------------------------------------------------------------- 1 | import * as minimatch from 'minimatch'; 2 | import * as _ from 'lodash'; 3 | 4 | export class AppElement extends HTMLElement { 5 | public static observedAttributes = []; 6 | 7 | connectedCallback() { 8 | this.innerHTML = ` 9 |
minimatch('lodash/*', 'lodash/step') -> ${minimatch( 10 | 'lodash/*', 11 | 'lodash/step' 12 | )}
13 |
_.camelCase('shared-library-webpack-plugin') -> ${_.camelCase( 14 | 'shared-library-webpack-plugin' 15 | )}
16 | `; 17 | } 18 | } 19 | 20 | customElements.define('shared-library-webpack-plugin-root', AppElement); 21 | -------------------------------------------------------------------------------- /apps/sandbox/src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tinkoff/shared-library-webpack-plugin/8c6bd84e020858886eaadd0cdcc9e8bb8b017b9b/apps/sandbox/src/assets/.gitkeep -------------------------------------------------------------------------------- /apps/sandbox/src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true, 3 | }; 4 | -------------------------------------------------------------------------------- /apps/sandbox/src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // This file can be replaced during build by using the `fileReplacements` array. 2 | // When building for production, this file is replaced with `environment.prod.ts`. 3 | 4 | export const environment = { 5 | production: false, 6 | }; 7 | -------------------------------------------------------------------------------- /apps/sandbox/src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tinkoff/shared-library-webpack-plugin/8c6bd84e020858886eaadd0cdcc9e8bb8b017b9b/apps/sandbox/src/favicon.ico -------------------------------------------------------------------------------- /apps/sandbox/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Sandbox 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /apps/sandbox/src/main.ts: -------------------------------------------------------------------------------- 1 | import './app/app.element.ts'; 2 | -------------------------------------------------------------------------------- /apps/sandbox/src/polyfills.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Polyfill stable language features. These imports will be optimized by `@babel/preset-env`. 3 | * 4 | * See: https://github.com/zloirock/core-js#babel 5 | */ 6 | import 'core-js/stable'; 7 | import 'regenerator-runtime/runtime'; 8 | 9 | import '@webcomponents/custom-elements/custom-elements.min'; 10 | import '@webcomponents/custom-elements/src/native-shim'; 11 | -------------------------------------------------------------------------------- /apps/sandbox/src/styles.scss: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | -------------------------------------------------------------------------------- /apps/sandbox/src/test-setup.ts: -------------------------------------------------------------------------------- 1 | import 'document-register-element'; 2 | -------------------------------------------------------------------------------- /apps/sandbox/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../../dist/out-tsc", 5 | "types": ["node"] 6 | }, 7 | "exclude": ["**/*.spec.ts"], 8 | "include": ["**/*.ts"] 9 | } 10 | -------------------------------------------------------------------------------- /apps/sandbox/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig.json", 3 | "compilerOptions": { 4 | "types": ["node", "jest"] 5 | }, 6 | "include": ["**/*.ts"] 7 | } 8 | -------------------------------------------------------------------------------- /apps/sandbox/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../../dist/out-tsc", 5 | "module": "commonjs", 6 | "types": ["jest", "node"] 7 | }, 8 | "files": ["src/test-setup.ts"], 9 | "include": ["**/*.spec.ts", "**/*.d.ts"] 10 | } 11 | -------------------------------------------------------------------------------- /apps/sandbox/webpack.config.js: -------------------------------------------------------------------------------- 1 | const { 2 | SharedLibraryWebpackPlugin, 3 | } = require('../../dist/libs/shared-library-webpack-plugin'); 4 | 5 | module.exports = function (config, { options }) { 6 | config.plugins.push( 7 | new SharedLibraryWebpackPlugin({ 8 | libs: ['minimatch', 'lodash'], 9 | }) 10 | ); 11 | 12 | return config; 13 | }; 14 | -------------------------------------------------------------------------------- /code_of_conduct.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or 20 | 21 | advances 22 | 23 | * Trolling, insulting/derogatory comments, and personal or political attacks 24 | * Public or private harassment 25 | * Publishing others' private information, such as a physical or electronic 26 | 27 | address, without explicit permission 28 | 29 | * Other conduct which could reasonably be considered inappropriate in a 30 | 31 | professional setting 32 | 33 | ## Our Responsibilities 34 | 35 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 36 | 37 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 38 | 39 | ## Scope 40 | 41 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 42 | 43 | ## Enforcement 44 | 45 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at opensource@tinkoff.ru. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 46 | 47 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 48 | 49 | ## Attribution 50 | 51 | This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 1.4, available at [https://www.contributor-covenant.org/version/1/4/code-of-conduct.html](https://www.contributor-covenant.org/version/1/4/code-of-conduct.html) 52 | 53 | For answers to common questions about this code of conduct, see [https://www.contributor-covenant.org/faq](https://www.contributor-covenant.org/faq) 54 | 55 | -------------------------------------------------------------------------------- /contributing.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | > Thank you for considering contributing to our project. Your help if very welcome! 4 | 5 | When contributing, it's better to first discuss the change you wish to make via issue, email, or any other method with the owners of this repository before making a change. 6 | 7 | All members of our community are expected to follow our [Code of Conduct](code_of_conduct.md). Please make sure you are welcoming and friendly in all of our spaces. 8 | 9 | ## Getting started 10 | 11 | In order to make your contribution please make a fork of the repository. After you've pulled the code, follow these steps to kick start the development: 12 | 13 | 1. Run `npm i` to install dependencies 14 | 2. Run `npm start` to launch demo project where you could test your changes 15 | 3. Use following commands to ensure code quality 16 | 17 | ```text 18 | npm run lint 19 | npm run build 20 | npm run test 21 | ``` 22 | 23 | ## Pull Request Process 24 | 25 | 1. We follow [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0-beta.4/) 26 | 27 | in our commit messages, i.e. `feat(core): improve typing` 28 | 29 | 2. Update [README.md](./) to reflect changes related to public API and everything relevant 30 | 3. Make sure you cover all code changes with unit tests 31 | 4. When you are ready, create Pull Request of your fork into original repository 32 | 33 | -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- 1 | # Documentation 2 | 3 | -------------------------------------------------------------------------------- /docs/how_does_it_work.md: -------------------------------------------------------------------------------- 1 | # How does it work? 2 | 3 | ## How the plugin works 4 | 5 | 1. The plugin analyzes chunks and extracts libraries to separated chunks with disabled tree-shaking \([or not?](tree_shaing.md)\). 6 | 2. The plugin teaches entries and runtime to work with shared chunks. 7 | 8 | ## How the app is loaded 9 | 10 | 1. Entry points and runtime are loaded. 11 | 2. Entry point checks if a shared required to run chunks are loaded and notifies the runtime about it. 12 | 3. Runtime downloads all not downloaded libraries and marks them as downloaded. 13 | 4. Runtime runs an app. 14 | 15 | -------------------------------------------------------------------------------- /docs/installation_and_configuration.md: -------------------------------------------------------------------------------- 1 | # Installation and Configuration 2 | 3 | ## Installation 4 | 5 | The plugin can install by any package manager. 6 | 7 | ```text 8 | npm i @tinkoff/shared-library-webpack-plugin -D 9 | ``` 10 | 11 | or 12 | 13 | ```text 14 | yarn add @tinkoff/shared-library-webpack-plugin --dev 15 | ``` 16 | 17 | ## Configuration 18 | 19 | Add plugin to webpack configuration file and set a list of libraries for sharing. There is an example with `lodash`: 20 | 21 | ```typescript 22 | import { SharedLibraryWebpackPlugin } from '@tinkoff/shared-library-webpack-plugin'; 23 | 24 | module.exports = { 25 | plugin: [ 26 | new SharedLibraryWebpackPlugin({ 27 | libs: 'lodash', 28 | }), 29 | ], 30 | }; 31 | ``` 32 | 33 | The plugin adds one more chunk with a hashed name to the bundle. It should be a shared lodash. When the application is loaded, the webpack runtime will check if lodash is loaded. 34 | 35 | ## [How does it work?](how_does_it_work.md) 36 | 37 | -------------------------------------------------------------------------------- /docs/the_plugin.md: -------------------------------------------------------------------------------- 1 | # The Plugin 2 | 3 | ## `SharedLibraryWebpackPlugin` 4 | 5 | `SharedLibraryWebpackPlugin` is a class that implements webpack plugin functionality, 6 | 7 | ## Options 8 | 9 | #### `libs` 10 | 11 | {% tabs %} 12 | {% tab title="Description" %} 13 | `string | SharedLibrarySearchConfig | Array` 14 | 15 | An option that configures the search for shared libraries and the formation of a chunk name. It can be a string or [SharedLibrarySearchConfig](the_plugin.md#sharedlibrarysearchconfig) or an array of them. 16 | {% endtab %} 17 | 18 | {% tab title="Example" %} 19 | ```typescript 20 | new SharedLibraryWebpackPlugin({ 21 | libs: 'lodash' 22 | }); 23 | 24 | new SharedLibraryWebpackPlugin({ 25 | libs: '@angular/**' 26 | }); 27 | 28 | new SharedLibraryWebpackPlugin({ 29 | libs: ['@angular/**', 'zone.js/dist/zone'] 30 | }); 31 | 32 | new SharedLibraryWebpackPlugin({ 33 | libs: {name: '@angular/core', chunkName: 'ng', separator: '@'} 34 | }); 35 | ``` 36 | {% endtab %} 37 | {% endtabs %} 38 | 39 | #### `namespace` 40 | 41 | {% tabs %} 42 | {% tab title="Description" %} 43 | `string` 44 | 45 | The namespace for saving exported libraries 46 | {% endtab %} 47 | 48 | {% tab title="Example" %} 49 | ```typescript 50 | { 51 | namespace: "__shared_libraries__" 52 | } 53 | ``` 54 | {% endtab %} 55 | {% endtabs %} 56 | 57 | #### `disableDefaultJsonpFunctionChange` 58 | 59 | {% tabs %} 60 | {% tab title="Description" %} 61 | `boolean` 62 | 63 | By default: `false` 64 | 65 | If true `jsonpFunction` will be replaced with a random name 66 | {% endtab %} 67 | 68 | {% tab title="Example" %} 69 | ```typescript 70 | { 71 | disableDefaultJsonpFunctionChange: false 72 | } 73 | ``` 74 | {% endtab %} 75 | {% endtabs %} 76 | 77 | ### `SharedLibrarySearchConfig` 78 | 79 | `SharedLibrarySearchConfig` configures the search for sharing library and the formation of a chunk name. 80 | 81 | #### `pattern` 82 | 83 | {% tabs %} 84 | {% tab title="Description" %} 85 | `string` 86 | 87 | An option to search for libraries in a bundle. 88 | {% endtab %} 89 | 90 | {% tab title="Example" %} 91 | ```typescript 92 | { 93 | pattern: "@angular/**" 94 | } 95 | ``` 96 | {% endtab %} 97 | {% endtabs %} 98 | 99 | #### `name` 100 | 101 | {% tabs %} 102 | {% tab title="Description" %} 103 | `string` 104 | 105 | A name to search for a library in a bundle. 106 | {% endtab %} 107 | 108 | {% tab title="Example" %} 109 | ```typescript 110 | { 111 | name: "@angular/core" 112 | } 113 | ``` 114 | {% endtab %} 115 | {% endtabs %} 116 | 117 | #### `chunkName` 118 | 119 | {% tabs %} 120 | {% tab title="Description" %} 121 | `string` 122 | 123 | A name of a shared chunk 124 | 125 | {% hint style="info" %} 126 | If a pattern exists `chunkName` is ignored 127 | {% endhint %} 128 | {% endtab %} 129 | 130 | {% tab title="Example" %} 131 | ```typescript 132 | { 133 | chunkName: "ng" 134 | } 135 | ``` 136 | {% endtab %} 137 | {% endtabs %} 138 | 139 | #### `suffix` 140 | 141 | {% tabs %} 142 | {% tab title="Description" %} 143 | `string` 144 | 145 | A chunk name suffix 146 | 147 | By default library version `{major}.{minor}-{prerelease}` 148 | {% endtab %} 149 | 150 | {% tab title="Example" %} 151 | ```typescript 152 | { 153 | suffix: 'suffix' 154 | } 155 | ``` 156 | {% endtab %} 157 | {% endtabs %} 158 | 159 | #### `separator` 160 | 161 | {% tabs %} 162 | {% tab title="Description" %} 163 | `string` 164 | 165 | Separator for a chunk name and suffix 166 | {% endtab %} 167 | 168 | {% tab title="Example" %} 169 | ```typescript 170 | { 171 | separator: "@" 172 | } 173 | ``` 174 | {% endtab %} 175 | {% endtabs %} 176 | 177 | #### `deps` 178 | 179 | {% tabs %} 180 | {% tab title="Description" %} 181 | `string[]` 182 | 183 | Libraries that the current one depends on. 184 | {% endtab %} 185 | 186 | {% tab title="Example" %} 187 | ```typescript 188 | new SharedLibraryWebpackPlugin({ 189 | libs: [ 190 | '@angular/**', 191 | {name: '@tinkoff/angular-ui', deps: ['@angular/core']} 192 | ] 193 | }) 194 | ``` 195 | {% endtab %} 196 | {% endtabs %} 197 | 198 | #### `usedExports` 199 | 200 | {% tabs %} 201 | {% tab title="Description" %} 202 | `string[]` 203 | 204 | The import names to be used by another application 205 | {% endtab %} 206 | 207 | {% tab title="Example" %} 208 | ```typescript 209 | {name: '@angular/core', usedExports: ['DomSanitizer']} 210 | ``` 211 | {% endtab %} 212 | {% endtabs %} 213 | 214 | -------------------------------------------------------------------------------- /docs/tree_shaing.md: -------------------------------------------------------------------------------- 1 | # Sharing and Tree shaking 2 | 3 | Tree shaking is dead-code elimination. [Read more](https://webpack.js.org/guides/tree-shaking/) 4 | 5 | Because the plugin doesn't know which the library part will use in another application, it disabled tree shaking. Therefore bundles become large. 6 | 7 | For the solution, the plugin provides an usedExports option. It can be an array of import names to be used by another application. See the example in [the demo](https://github.com/IKatsuba/shared-library-plugin-demo/blob/master/apps/code-of-conduct/extra-webpack.config.js). 8 | 9 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | testMatch: ['**/+(*.)+(spec|test).+(ts|js)?(x)'], 3 | transform: { 4 | '^.+\\.(ts|js|html)$': 'ts-jest', 5 | }, 6 | resolver: '@nrwl/jest/plugins/resolver', 7 | moduleFileExtensions: ['ts', 'js', 'html'], 8 | coverageReporters: ['html'], 9 | testEnvironment: 'node', 10 | }; 11 | -------------------------------------------------------------------------------- /libs/shared-library-webpack-plugin/.eslintrc: -------------------------------------------------------------------------------- 1 | { "extends": "../../.eslintrc", "rules": {}, "ignorePatterns": ["!**/*"] } 2 | -------------------------------------------------------------------------------- /libs/shared-library-webpack-plugin/.gitignore: -------------------------------------------------------------------------------- 1 | # test output 2 | __tests__/output 3 | -------------------------------------------------------------------------------- /libs/shared-library-webpack-plugin/__tests__/1.js: -------------------------------------------------------------------------------- 1 | import * as _ from 'lodash'; 2 | 3 | console.log(_); 4 | -------------------------------------------------------------------------------- /libs/shared-library-webpack-plugin/__tests__/2.js: -------------------------------------------------------------------------------- 1 | import last from 'lodash/lastIndexOf'; 2 | import * as minimatch from 'minimatch'; 3 | 4 | console.log(last); 5 | console.log(minimatch); 6 | -------------------------------------------------------------------------------- /libs/shared-library-webpack-plugin/__tests__/3.js: -------------------------------------------------------------------------------- 1 | import { HttpClient } from '@angular/common/http'; 2 | import { CommonModule } from '@angular/common'; 3 | 4 | console.log(HttpClient); 5 | console.log(CommonModule); 6 | -------------------------------------------------------------------------------- /libs/shared-library-webpack-plugin/jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | name: 'shared-library-webpack-plugin', 3 | preset: '../../jest.config.js', 4 | transform: { 5 | '^.+\\.[tj]sx?$': 'ts-jest', 6 | }, 7 | moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'html'], 8 | coverageDirectory: '../../coverage/libs/shared-library-webpack-plugin', 9 | }; 10 | -------------------------------------------------------------------------------- /libs/shared-library-webpack-plugin/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@tinkoff/shared-library-webpack-plugin", 3 | "version": "0.0.0-development.0", 4 | "license": "Apache-2.0", 5 | "keywords": [ 6 | "shared", 7 | "library", 8 | "webpack", 9 | "plugin" 10 | ], 11 | "author": "Igor Katsuba ", 12 | "description": "Webpack plugin for library sharing at runtime between applications", 13 | "publishConfig": { 14 | "access": "public" 15 | }, 16 | "repository": { 17 | "type": "git", 18 | "url": "git+https://github.com/TinkoffCreditSystems/shared-library-webpack-plugin.git" 19 | }, 20 | "bugs": { 21 | "url": "https://github.com/TinkoffCreditSystems/shared-library-webpack-plugin/issues" 22 | }, 23 | "homepage": "https://github.com/TinkoffCreditSystems/shared-library-webpack-plugin#readme", 24 | "dependencies": { 25 | "uuid": "^8.1.0", 26 | "jscodeshift": "^0.9.0", 27 | "lodash": "^4.17.15" 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /libs/shared-library-webpack-plugin/src/index.ts: -------------------------------------------------------------------------------- 1 | export * from './lib/shared-library-webpack-plugin'; 2 | -------------------------------------------------------------------------------- /libs/shared-library-webpack-plugin/src/lib/shared-library-webpack-plugin.spec.ts: -------------------------------------------------------------------------------- 1 | import { SharedLibraryWebpackPlugin } from './shared-library-webpack-plugin'; 2 | import * as webpack from 'webpack'; 3 | import { Stats } from 'webpack'; 4 | import { resolve } from 'path'; 5 | import * as fs from 'fs'; 6 | import * as jscodeshift from 'jscodeshift'; 7 | import { Collection } from 'jscodeshift/src/Collection'; 8 | import * as puppeteer from 'puppeteer'; 9 | import { Browser, Page, Request, ResourceType } from 'puppeteer'; 10 | import { MonoTypeOperatorFunction, Observable, Subscription } from 'rxjs'; 11 | import { filter } from 'rxjs/operators'; 12 | 13 | const commonWebpackConfig: webpack.Configuration = { 14 | output: { 15 | path: resolve(__dirname, '../../__tests__/output'), 16 | }, 17 | mode: 'production', 18 | optimization: { 19 | runtimeChunk: { 20 | name: 'runtime', 21 | }, 22 | }, 23 | performance: false, 24 | devtool: 'source-map', 25 | }; 26 | 27 | function webpackCallbackFactory( 28 | success: (stats: Stats) => void = () => {} // eslint-disable-line 29 | ): webpack.Compiler.Handler { 30 | return function webpackCallback(err: Error, stats: Stats) { 31 | if (err) { 32 | throw err; 33 | } 34 | 35 | const { errors, warnings } = stats.compilation; 36 | 37 | warnings.forEach(console.warn); 38 | 39 | if (errors?.length) { 40 | const [firstError, ...nextErrors] = errors; 41 | 42 | nextErrors.forEach(console.error); 43 | throw firstError; 44 | } 45 | 46 | success(stats); 47 | }; 48 | } 49 | 50 | const DEFAULT_WEBPACK_JSONP_FN_NAME = 'webpackJsonp'; 51 | 52 | function runWebpack(config: webpack.Configuration): Promise { 53 | return new Promise((resolve) => { 54 | webpack({ 55 | ...commonWebpackConfig, 56 | ...config, 57 | }).run( 58 | webpackCallbackFactory((stats) => { 59 | resolve(stats); 60 | }) 61 | ); 62 | }); 63 | } 64 | 65 | function getChunkSource(assetName: string) { 66 | return fs 67 | .readFileSync(resolve(__dirname, `../../__tests__/output/${assetName}`)) 68 | .toString(); 69 | } 70 | 71 | function getChunkAST(assetName: string): Collection { 72 | return jscodeshift(getChunkSource(assetName)); 73 | } 74 | 75 | function windowWithNamespaceIsExist(namespace: string): boolean | never { 76 | const ast = getChunkAST('runtime.js'); 77 | return ast 78 | .find(jscodeshift.MemberExpression) 79 | .filter((path) => { 80 | const expression = path.value; 81 | 82 | return ( 83 | expression.object.type === 'Identifier' && 84 | expression.object.name === 'window' && 85 | expression.property.type === 'Identifier' && 86 | expression.property.name === namespace 87 | ); 88 | }) 89 | .get(0); 90 | } 91 | 92 | function filterByResourceType( 93 | types: ResourceType[] 94 | ): MonoTypeOperatorFunction { 95 | return filter((request: Request) => 96 | types.includes(request.resourceType()) 97 | ); 98 | } 99 | 100 | describe('SharedLibraryWebpackPlugin', () => { 101 | describe('Конфигурация libs', () => { 102 | it('Если в libs передать строку, то на выходе получим массив конфигов с одним элементом', function () { 103 | expect(new SharedLibraryWebpackPlugin({ libs: 'lib' }).libs).toEqual([ 104 | { 105 | deps: [], 106 | pattern: 'lib', 107 | separator: '-', 108 | suffix: "${major}.${minor}${prerelease ? '-' + prerelease : ''}", 109 | }, 110 | ]); 111 | }); 112 | 113 | it('Все строки в libs приводятся к объекту, все объекты расширяются дефолтными свойствами', function () { 114 | expect( 115 | new SharedLibraryWebpackPlugin({ 116 | libs: [ 117 | 'lib', 118 | { name: 'lib2' }, 119 | { deps: ['lib3'], pattern: 'lib/*', separator: '.' }, 120 | ], 121 | }).libs 122 | ).toEqual([ 123 | { 124 | deps: [], 125 | pattern: 'lib', 126 | separator: '-', 127 | suffix: "${major}.${minor}${prerelease ? '-' + prerelease : ''}", 128 | }, 129 | { 130 | deps: [], 131 | name: 'lib2', 132 | separator: '-', 133 | suffix: "${major}.${minor}${prerelease ? '-' + prerelease : ''}", 134 | }, 135 | { 136 | deps: ['lib3'], 137 | pattern: 'lib/*', 138 | separator: '.', 139 | suffix: "${major}.${minor}${prerelease ? '-' + prerelease : ''}", 140 | }, 141 | ]); 142 | }); 143 | }); 144 | 145 | describe('Плагин инициализирован и в libs указанно одно имя модуля', () => { 146 | let stats: Stats; 147 | 148 | beforeAll(() => { 149 | return runWebpack({ 150 | entry: { entry: resolve(__dirname, '../../__tests__/1.js') }, 151 | plugins: [ 152 | new SharedLibraryWebpackPlugin({ 153 | libs: 'lodash', 154 | disableDefaultJsonpFunctionChange: true, 155 | }), 156 | ], 157 | }).then((compilationStats) => { 158 | stats = compilationStats; 159 | }); 160 | }); 161 | 162 | it('На выходе получаем три чанка', () => { 163 | const { assetsByChunkName } = stats.toJson(); 164 | 165 | expect(assetsByChunkName).toEqual({ 166 | entry: ['entry.js', 'entry.js.map'], 167 | 'lodash-4.17.e440fc': [ 168 | 'lodash-4.17.e440fc.js', 169 | 'lodash-4.17.e440fc.js.map', 170 | ], 171 | runtime: ['runtime.js', 'runtime.js.map'], 172 | }); 173 | }); 174 | 175 | it('entry не должен содержать динамический чанк', () => { 176 | const { entrypoints } = stats.toJson(); 177 | 178 | expect(entrypoints.entry.assets).toEqual([ 179 | 'runtime.js', 180 | 'runtime.js.map', 181 | 'entry.js', 182 | 'entry.js.map', 183 | ]); 184 | }); 185 | 186 | it('Глобальный неймспейс для шаринга имеет дефолтное имя', () => { 187 | expect( 188 | windowWithNamespaceIsExist( 189 | SharedLibraryWebpackPlugin.defaultSharedLibraryNamespace 190 | ) 191 | ).toBeTruthy(); 192 | }); 193 | 194 | it('Имя jsonpFunction не изменено', () => { 195 | expect(stats.compilation.outputOptions.jsonpFunction).toEqual( 196 | DEFAULT_WEBPACK_JSONP_FN_NAME 197 | ); 198 | }); 199 | 200 | it('Check outputs', () => { 201 | const { assets } = stats.toJson(); 202 | 203 | assets.forEach(({ name }) => { 204 | expect(getChunkSource(name)).toMatchSnapshot(); 205 | }); 206 | }); 207 | }); 208 | 209 | describe('Плагин инициализирован и в libs указанно несколько конфигов', () => { 210 | const anotherNamespace = '__another_name__'; 211 | let stats: Stats; 212 | 213 | beforeAll(() => { 214 | return runWebpack({ 215 | entry: { entry: resolve(__dirname, '../../__tests__/2.js') }, 216 | plugins: [ 217 | new SharedLibraryWebpackPlugin({ 218 | libs: ['lodash/**', { name: 'minimatch', deps: ['lodash'] }], 219 | namespace: anotherNamespace, 220 | }), 221 | ], 222 | }).then((compilationStats) => { 223 | stats = compilationStats; 224 | }); 225 | }); 226 | 227 | it('Имя jsonpFunction изменено на случайное', () => { 228 | expect(stats.compilation.outputOptions.jsonpFunction).not.toEqual( 229 | DEFAULT_WEBPACK_JSONP_FN_NAME 230 | ); 231 | }); 232 | 233 | it('На выходе получаем 4 чанка. Имена формируются с учетом зависимостей', () => { 234 | const { assetsByChunkName } = stats.toJson(); 235 | 236 | expect(assetsByChunkName).toEqual({ 237 | entry: ['entry.js', 'entry.js.map'], 238 | 'lodashLastIndexOf-4.17.f151b0': [ 239 | 'lodashLastIndexOf-4.17.f151b0.js', 240 | 'lodashLastIndexOf-4.17.f151b0.js.map', 241 | ], 242 | 'minimatch-3.0-lodash-4.17.d8bc20': [ 243 | 'minimatch-3.0-lodash-4.17.d8bc20.js', 244 | 'minimatch-3.0-lodash-4.17.d8bc20.js.map', 245 | ], 246 | runtime: ['runtime.js', 'runtime.js.map'], 247 | }); 248 | }); 249 | 250 | it('entry не должен содержать динамические чанки', () => { 251 | const { entrypoints } = stats.toJson(); 252 | 253 | expect(entrypoints.entry.assets).toEqual([ 254 | 'runtime.js', 255 | 'runtime.js.map', 256 | 'entry.js', 257 | 'entry.js.map', 258 | ]); 259 | }); 260 | 261 | it('Глобальный неймспейс для шаринга имеет кастомное имя', () => { 262 | expect(windowWithNamespaceIsExist(anotherNamespace)).toBeTruthy(); 263 | }); 264 | }); 265 | 266 | describe('Angular and secondary entry points', () => { 267 | let stats: Stats; 268 | 269 | beforeAll(() => { 270 | return runWebpack({ 271 | entry: { entry: resolve(__dirname, '../../__tests__/3.js') }, 272 | plugins: [ 273 | new SharedLibraryWebpackPlugin({ 274 | libs: [ 275 | { name: '@angular/common', usedExports: ['APP_BASE_HREF'] }, 276 | '@angular/**', 277 | ], 278 | disableDefaultJsonpFunctionChange: true, 279 | }), 280 | ], 281 | }).then((compilationStats) => { 282 | stats = compilationStats; 283 | }); 284 | }, 10_000); 285 | 286 | it('@angular/common и @angular/common/http каждый в своем чанке', () => { 287 | const { assetsByChunkName } = stats.toJson(); 288 | 289 | expect(assetsByChunkName).toEqual({ 290 | 'angularCommon-10.0.1304b2': [ 291 | 'angularCommon-10.0.1304b2.js', 292 | 'angularCommon-10.0.1304b2.js.map', 293 | ], 294 | 'angularCommonHttp-10.0.05f38d': [ 295 | 'angularCommonHttp-10.0.05f38d.js', 296 | 'angularCommonHttp-10.0.05f38d.js.map', 297 | ], 298 | 'angularCore-10.0.a9e392': [ 299 | 'angularCore-10.0.a9e392.js', 300 | 'angularCore-10.0.a9e392.js.map', 301 | ], 302 | entry: ['entry.js', 'entry.js.map'], 303 | runtime: ['runtime.js', 'runtime.js.map'], 304 | }); 305 | }); 306 | 307 | it('Check outputs', () => { 308 | const { assets } = stats.toJson(); 309 | 310 | assets.forEach(({ name }) => { 311 | expect(getChunkSource(name)).toMatchSnapshot(); 312 | }); 313 | }); 314 | }); 315 | 316 | describe('Проверка загрузки и исполнения скриптов', () => { 317 | let browser: Browser; 318 | let page: Page; 319 | let requests: Observable; 320 | let subscription: Subscription; 321 | 322 | beforeAll(async () => { 323 | browser = await puppeteer.launch(); 324 | }); 325 | 326 | beforeEach(async () => { 327 | page = await browser.newPage(); 328 | 329 | subscription = new Subscription(); 330 | 331 | requests = new Observable((subscriber) => { 332 | const handler = (request: Request) => { 333 | request.continue(); 334 | subscriber.next(request); 335 | }; 336 | 337 | page.on('request', handler); 338 | 339 | return () => { 340 | page.removeListener('request', handler); 341 | subscriber.unsubscribe(); 342 | }; 343 | }); 344 | }); 345 | 346 | it('Чанк с minimatch грузится только после mine.js', async () => { 347 | let mainIsLoaded = false; 348 | let minimatchIsLoaded = false; 349 | 350 | subscription.add( 351 | requests.pipe(filterByResourceType(['script'])).subscribe((request) => { 352 | if (request.url().endsWith('/main.js')) { 353 | expect(minimatchIsLoaded).toBeFalsy(); 354 | mainIsLoaded = true; 355 | } 356 | 357 | if (request.url().endsWith('/bfeb3267488c3cf7faa6192c5b296d69.js')) { 358 | expect(mainIsLoaded).toBeTruthy(); 359 | minimatchIsLoaded = true; 360 | } 361 | }) 362 | ); 363 | 364 | await page.setRequestInterception(true); 365 | await page.goto('http://localhost:4200'); 366 | }); 367 | 368 | it('После загрузки появляется глобальное имя с расшаренным minimatch', async () => { 369 | await page.goto('http://localhost:4200'); 370 | 371 | const minimatchIsExists = await page.evaluate( 372 | () => !!window['__shared_libs_b8__']['minimatch-3.0.d8bc20'] 373 | ); 374 | 375 | expect(minimatchIsExists).toBeTruthy(); 376 | }); 377 | 378 | describe('Эмуляция уже загруженного lodash 4.17', () => { 379 | beforeEach(async () => { 380 | await page.evaluateOnNewDocument(() => { 381 | window['__shared_libs_b8__'] = {}; 382 | window['__shared_libs_b8__']['lodash-4.17.e440fc'] = 383 | window['__shared_libs_b8__']['lodash-4.17.e440fc'] || {}; 384 | window['__shared_libs_b8__']['lodash-4.17.e440fc']['60bb'] = { 385 | exports: { 386 | camelCase() { 387 | return 'There is sharing!'; 388 | }, 389 | }, 390 | }; 391 | }); 392 | }); 393 | 394 | it('Chunk lodash 4.17 не грузиться', async () => { 395 | subscription.add( 396 | requests 397 | .pipe(filterByResourceType(['script'])) 398 | .subscribe((request) => { 399 | expect(request.url().endsWith('/lodash-4.17.js')).toBeFalsy(); 400 | }) 401 | ); 402 | 403 | await page.setRequestInterception(true); 404 | await page.goto('http://localhost:4200'); 405 | }); 406 | 407 | it('В теле документа нет скрипта lodash', async () => { 408 | await page.goto('http://localhost:4200'); 409 | 410 | const scripts = await page.$$eval('script', (elements) => 411 | elements.map((element) => element.getAttribute('src')) 412 | ); 413 | 414 | expect(scripts).toStrictEqual([ 415 | 'minimatch-3.0.d8bc20.js', 416 | 'runtime.js', 417 | 'styles.js', 418 | 'main.js', 419 | ]); 420 | }); 421 | 422 | it('Выводится сообщение из мока lodash', async () => { 423 | await page.goto('http://localhost:4200'); 424 | 425 | const text = await page.$eval( 426 | '.lodash-message', 427 | (element) => element.textContent 428 | ); 429 | 430 | expect(text).toEqual('There is sharing!'); 431 | }); 432 | }); 433 | 434 | describe('Эмуляция уже загруженного lodash 4.16', () => { 435 | beforeEach(async () => { 436 | await page.evaluateOnNewDocument(() => { 437 | window['__shared_libs_b8__'] = {}; 438 | window['__shared_libs_b8__']['lodash-4.16'] = { 439 | exports: { 440 | camelCase() { 441 | return 'There is sharing!'; 442 | }, 443 | }, 444 | }; 445 | }); 446 | }); 447 | 448 | it('Чанк с lodash 4.17 грузиться', async () => { 449 | let lodashIsLoaded = false; 450 | 451 | subscription.add( 452 | requests 453 | .pipe(filterByResourceType(['script'])) 454 | .subscribe((request) => { 455 | if (request.url().endsWith('/lodash-4.17.e440fc.js')) { 456 | lodashIsLoaded = true; 457 | } 458 | }) 459 | ); 460 | 461 | await page.setRequestInterception(true); 462 | await page.goto('http://localhost:4200'); 463 | 464 | expect(lodashIsLoaded).toBeTruthy(); 465 | }); 466 | 467 | it('В теле документа есть скрипт lodash 4.17', async () => { 468 | await page.goto('http://localhost:4200'); 469 | 470 | const scripts = await page.$$eval('script', (elements) => 471 | elements.map((element) => element.getAttribute('src')) 472 | ); 473 | 474 | expect(scripts).toStrictEqual([ 475 | 'minimatch-3.0.d8bc20.js', 476 | 'lodash-4.17.e440fc.js', 477 | 'runtime.js', 478 | 'styles.js', 479 | 'main.js', 480 | ]); 481 | }); 482 | 483 | it('Выводится сообщение из lodash 4.17', async () => { 484 | await page.goto('http://localhost:4200'); 485 | 486 | const text = await page.$eval( 487 | '.lodash-message', 488 | (element) => element.textContent 489 | ); 490 | 491 | expect(text).toEqual('sharedLibraryWebpackPlugin'); 492 | }); 493 | }); 494 | 495 | describe('Местонахождение скриптов в html-документе', () => { 496 | it('В body только entry points', async () => { 497 | await page.goto('http://localhost:4200'); 498 | 499 | const scripts = await page.$$eval('body script', (elements) => 500 | elements.map((element) => element.getAttribute('src')) 501 | ); 502 | 503 | expect(scripts).toEqual(['runtime.js', 'styles.js', 'main.js']); 504 | }); 505 | 506 | it('В head добавляются только чанки для шаринга', async () => { 507 | await page.goto('http://localhost:4200'); 508 | 509 | const scripts = await page.$$eval('head script', (elements) => 510 | elements.map((element) => element.getAttribute('src')) 511 | ); 512 | 513 | expect(scripts).toEqual([ 514 | 'minimatch-3.0.d8bc20.js', 515 | 'lodash-4.17.e440fc.js', 516 | ]); 517 | }); 518 | }); 519 | 520 | afterEach(() => { 521 | subscription.unsubscribe(); 522 | page.close(); 523 | }); 524 | 525 | afterAll(() => { 526 | browser.close(); 527 | }); 528 | }); 529 | }); 530 | -------------------------------------------------------------------------------- /libs/shared-library-webpack-plugin/src/lib/shared-library-webpack-plugin.ts: -------------------------------------------------------------------------------- 1 | import * as jscodeshift from 'jscodeshift'; 2 | import { camelCase, isNil } from 'lodash'; 3 | import { Hook } from 'tapable'; 4 | import { compilation, Compiler, Logger, Plugin } from 'webpack'; 5 | import { ConcatSource, Source } from 'webpack-sources'; 6 | import * as minimatch from 'minimatch'; 7 | import { parse } from 'path'; 8 | import { v4 as uuidV4 } from 'uuid'; 9 | 10 | import { 11 | compileSuffix, 12 | createUniqueHash, 13 | enforceSourceToString, 14 | findClosestPackageJsonWithVersion, 15 | getPackageVersion, 16 | getTapFor, 17 | isFnWithName, 18 | } from './utils'; 19 | import { createHash } from 'crypto'; 20 | 21 | type ModuleWithDeps = compilation.Module & 22 | WithDeps & { 23 | userRequest: string; 24 | rawRequest?: string; 25 | }; 26 | 27 | /** 28 | * webpack фиговенько затипизирован, по этому иногда приходиться писать типы, которых нет 29 | */ 30 | type AddChunk = (name: string) => compilation.Chunk; 31 | 32 | interface WithDeps { 33 | dependencies: { module: ModuleWithDeps | null }[]; 34 | } 35 | 36 | /** 37 | * Конфиг, по которому происходит формирование и выделение анка под расшаренную 38 | * библиотеку. 39 | * 40 | * Если задан паттерн, то chunkName игнорируется. 41 | * 42 | * По приоритету сначала пытаемся либу сопоставить с name, потом с pattern. 43 | */ 44 | export interface SharedLibrarySearchConfig { 45 | /** 46 | * @see https://github.com/isaacs/minimatch 47 | */ 48 | pattern?: string; 49 | /** 50 | * Бибилиотеки для выделения 51 | */ 52 | name?: string; 53 | /** 54 | * Имя чанка под библиотеку и название поля в глобальном объекте для сохранения импорта. 55 | * Если chunkName не задан, берется name и пропускается через _.camelCase 56 | * Для pattern свойство игнорируется 57 | * 58 | * Webpack может сам вырезать некоторые символы из имен. 59 | */ 60 | chunkName?: string; 61 | /** 62 | * Суффикс имени чанка. 63 | * По дефолту это весрия библиотеки без патча {major}.{minor}-{prerelease} 64 | */ 65 | suffix?: string; 66 | 67 | /** 68 | * Сепаратор для имени чанка и суффикса 69 | */ 70 | separator?: string; 71 | 72 | /** 73 | * Библиотеки, от которых зависит текущая. 74 | * Имя чанка будет формироваться с учетом версии зависимости 75 | * 76 | * @example 77 | * new SharedLibraryWebpackPlugin({ 78 | * libs: ['@angular/**', {name: '@tinkoff/angular-ui', deps: ['@angular/core']}] 79 | * }) 80 | * 81 | * // chunkName => angularAnimationsBrowser-8.2-ngrxStore-7.4 82 | */ 83 | deps?: string[]; 84 | usedExports?: string[]; 85 | } 86 | 87 | /** 88 | * Конфигурация плагина 89 | */ 90 | export interface SharedLibraryWebpackPluginOptions { 91 | /** 92 | * Неймспейс в глобальном простарнстве для хранения экспортов либ для шаринга 93 | * Default: '__shared_libs__' 94 | */ 95 | namespace?: string; 96 | /** 97 | * Список библиотек для шаринга 98 | * Поддерживаются паттерны [minimatch]{@link https://github.com/isaacs/minimatch#readme} 99 | * 100 | * @example 101 | * { 102 | * libs: ['@angular/*', 'lodash'] 103 | * } 104 | * 105 | * { 106 | * libs: '@angular/*' 107 | * } 108 | * 109 | * { 110 | * libs: {name: '@angular/core', chunkName: 'ng', separator: '@'} 111 | * } 112 | */ 113 | libs: 114 | | string 115 | | SharedLibrarySearchConfig 116 | | ReadonlyArray; 117 | 118 | /** 119 | * Если false и `output.jsonpFunction === webpackJsonp`, то jsonpFunction 120 | * будет изменен на рандомный идентификатор. 121 | * 122 | * Default: false 123 | */ 124 | disableDefaultJsonpFunctionChange?: boolean; 125 | } 126 | 127 | /** 128 | * Плагин для шаринга библиотек между приложениями 129 | */ 130 | export class SharedLibraryWebpackPlugin implements Plugin { 131 | public static readonly defaultSharedLibraryNamespace = '__shared_libs_b8__'; 132 | private static readonly defaultSharedLibrarySearch: SharedLibrarySearchConfig = { 133 | separator: '-', 134 | deps: [], 135 | suffix: "${major}.${minor}${prerelease ? '-' + prerelease : ''}", 136 | }; 137 | private static readonly moduleSeparator = '___module_separator___'; 138 | /** 139 | * {@see SharedLibraryWebpackPluginOptions#libs} 140 | */ 141 | public readonly libs: ReadonlyArray; 142 | /** 143 | * Список чанков с модулями для шаринга и соответсвующие им entry 144 | */ 145 | private readonly sharedChunksAndEntries = new Map< 146 | compilation.Chunk, 147 | compilation.ChunkGroup 148 | >(); 149 | /** 150 | * {@see SharedLibraryWebpackPluginOptions#namespace} 151 | */ 152 | private readonly namespace: string; 153 | private compilation: compilation.Compilation & { addChunk: AddChunk }; 154 | private readonly patchRequireFnCache = new Map(); 155 | private readonly disableDefaultJsonpFunctionChange: boolean; 156 | 157 | /** 158 | * @see SharedLibraryWebpackPluginOptions 159 | */ 160 | constructor({ 161 | namespace = SharedLibraryWebpackPlugin.defaultSharedLibraryNamespace, 162 | libs, 163 | disableDefaultJsonpFunctionChange = false, 164 | }: SharedLibraryWebpackPluginOptions) { 165 | this.namespace = namespace; 166 | this.libs = (Array.isArray(libs) 167 | ? (libs as Array) 168 | : [libs] 169 | ) 170 | .map((lib) => (typeof lib === 'string' ? { pattern: lib } : lib)) 171 | .map((lib) => ({ 172 | ...SharedLibraryWebpackPlugin.defaultSharedLibrarySearch, 173 | ...lib, 174 | })); 175 | this.disableDefaultJsonpFunctionChange = disableDefaultJsonpFunctionChange; 176 | } 177 | 178 | /** 179 | * Список либ для шаринга 180 | */ 181 | private get sharedChunks(): readonly compilation.Chunk[] { 182 | return [...this.sharedChunksAndEntries.keys()]; 183 | } 184 | 185 | /** 186 | * Список либ для шаринга и соответсвующие им entry 187 | */ 188 | private get sharedChunksAndEntriesAsArray(): readonly [ 189 | compilation.Chunk, 190 | compilation.ChunkGroup 191 | ][] { 192 | return [...this.sharedChunksAndEntries.entries()]; 193 | } 194 | 195 | /** 196 | * Глобальный объект для создания неймспейса. 197 | * Берем из общих настроек. 198 | */ 199 | private get globalObject(): string { 200 | return this.compilation.mainTemplate.outputOptions.globalObject; 201 | } 202 | 203 | private get logger(): Logger { 204 | return this.compilation.getLogger(SharedLibraryWebpackPlugin.name); 205 | } 206 | 207 | /** 208 | * Входная точка плагина 209 | * @param compiler 210 | */ 211 | apply(compiler: Compiler) { 212 | compiler.hooks.environment.tap(SharedLibraryWebpackPlugin.name, () => { 213 | // меняем конфиг jsonpFunction, если он дефолтный и изменение разрешено в конфигах плагина 214 | if ( 215 | !this.disableDefaultJsonpFunctionChange && 216 | compiler.options?.output?.jsonpFunction === 'webpackJsonp' 217 | ) { 218 | compiler.options.output.jsonpFunction = uuidV4(); 219 | } 220 | }); 221 | 222 | // Получаем инстанс текущей компиляции, сохраняем его для удобства в инстанс 223 | // плагина и запускаем инициализацию хуков 224 | compiler.hooks.thisCompilation.tap( 225 | getTapFor(SharedLibraryWebpackPlugin.name, 10), 226 | (compilation: compilation.Compilation) => { 227 | this.compilation = compilation as compilation.Compilation & { 228 | addChunk: AddChunk; 229 | }; 230 | 231 | this.initCompilationHooks(compiler); 232 | } 233 | ); 234 | } 235 | 236 | private initCompilationHooks(compiler: Compiler) { 237 | // chunk runtime.js 238 | // хук на изменения кода бутстрапа приложения 239 | ((this.compilation.mainTemplate.hooks as any) 240 | .bootstrap as Hook).tap( 241 | getTapFor(SharedLibraryWebpackPlugin.name, 10), 242 | (source: string | Source): string => this.patchRuntimeBootstrap(source) 243 | ); 244 | 245 | // chunk runtime.js 246 | // хук на изменения кода функции require 247 | ((this.compilation.mainTemplate.hooks as any) 248 | .require as Hook).tap( 249 | getTapFor(SharedLibraryWebpackPlugin.name, 10), 250 | (source: string | Source): string => this.patchRequireFn(source) 251 | ); 252 | 253 | // хук на изменения кода обвязки отдельных чанков 254 | ((this.compilation.chunkTemplate as any).hooks 255 | .render as Hook).tap( 256 | getTapFor(SharedLibraryWebpackPlugin.name, 10), 257 | (source: ConcatSource, chunk: compilation.Chunk): string | Source => 258 | this.patchModule(source, chunk) 259 | ); 260 | 261 | //хук на выделение либ для шаринга в отдельные чанки 262 | this.compilation.hooks.optimizeChunks.tap( 263 | getTapFor(SharedLibraryWebpackPlugin.name, 10), 264 | () => { 265 | this.libraryToChunk(); 266 | } 267 | ); 268 | 269 | //хэшируем все модули 270 | this.compilation.hooks.beforeModuleIds.tap( 271 | getTapFor(SharedLibraryWebpackPlugin.name, 10), 272 | (modules) => { 273 | for (const module of modules) { 274 | if (module.id === null && (module as any).libIdent) { 275 | const id = (module as any).libIdent({ 276 | context: compiler.options.context, 277 | }); 278 | 279 | module.id = createUniqueHash(id); 280 | } 281 | } 282 | } 283 | ); 284 | } 285 | 286 | /** 287 | * См. каменты в примере ниже 288 | * @example 289 | * function __webpack_require__(moduleId) { 290 | * 291 | * /********* 292 | * * Инъекция сюда 293 | * * Тут проверяем есть ли наш модуль в глобале и записываем его в уже установленные, 294 | * * если он есть 295 | * *********\/ 296 | * 297 | * // Check if module is in cache 298 | * if(installedModules[moduleId]) { 299 | * return installedModules[moduleId].exports; 300 | * } 301 | * // Create a new module (and put it into the cache) 302 | * var module = installedModules[moduleId] = { 303 | * i: moduleId, 304 | * l: false, 305 | * exports: {} 306 | * }; 307 | * 308 | * // Execute the module function 309 | * modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); 310 | * 311 | * // Flag the module as loaded 312 | * module.l = true; 313 | * 314 | * /********* 315 | * * Инъекция сюда 316 | * * Тут проверяем, не наш ли это модуль только что экспортировали, 317 | * * если наш, то зипихиваем его в глобал 318 | * *********\/ 319 | * // Return the exports of the module 320 | * return module.exports; 321 | * } 322 | * 323 | * @param source 324 | */ 325 | private patchRequireFn(source: string | Source): string { 326 | source = enforceSourceToString(source); 327 | 328 | if (this.patchRequireFnCache.has(source)) { 329 | return this.patchRequireFnCache.get(source); 330 | } 331 | 332 | const toInstalledModulesFromGlobal = this.sharedChunks 333 | .map((ch) => { 334 | return ` 335 | if(${JSON.stringify( 336 | [...ch.modulesIterable].map((m) => m.id) 337 | )}.indexOf(moduleId) > -1){ 338 | ${this.globalObject}['${this.namespace}'] = ${this.globalObject}['${ 339 | this.namespace 340 | }'] || {}; 341 | ${this.globalObject}['${this.namespace}']['${ch.name}'] = ${ 342 | this.globalObject 343 | }['${this.namespace}']['${ch.name}'] || {}; 344 | ${this.globalObject}['${this.namespace}']['${ch.name}'][moduleId] = module; 345 | }`; 346 | }) 347 | .join(''); 348 | 349 | const toGlobalFromInstalledModules = this.sharedChunks 350 | .map((ch) => { 351 | return ` 352 | if(${JSON.stringify( 353 | [...ch.modulesIterable].map((m) => m.id) 354 | )}.indexOf(moduleId) > -1 && ${this.globalObject}['${ 355 | this.namespace 356 | }'] && ${this.globalObject}['${this.namespace}']['${ch.name}'] && ${ 357 | this.globalObject 358 | }['${this.namespace}']['${ch.name}'][moduleId]){ 359 | installedModules[moduleId] = ${this.globalObject}['${this.namespace}']['${ 360 | ch.name 361 | }'][moduleId]; 362 | }`; 363 | }) 364 | .join(''); 365 | 366 | const ast = jscodeshift(source); 367 | 368 | ast 369 | .find(jscodeshift.ReturnStatement) 370 | .at(1) 371 | .insertBefore(toInstalledModulesFromGlobal); 372 | 373 | ast 374 | .find(jscodeshift.IfStatement) 375 | .at(0) 376 | .insertBefore(toGlobalFromInstalledModules); 377 | 378 | const result = ast.toSource(); 379 | 380 | this.patchRequireFnCache.set(source, result); 381 | 382 | return result; 383 | } 384 | 385 | /** 386 | * Стандартный врапер вокраг чанка выглядит примерно так: 387 | * 388 | * в массив window["webpackJsonp"] пушится массив с тремя элементами 389 | * 0. Содержит имя точки входа 390 | * 1. Сами модули 391 | * 2. Зависимости от других чанков и id точки входа 392 | * 393 | * В этом методе определяем имеет ли чанк зависимости от либ для шаринга. 394 | * Если да - добавляем эти либы в зависимости, то есть патчим элемент массива №2 395 | * 396 | * @example 397 | * (window["webpackJsonp"] = window["webpackJsonp"] || []).push([ 398 | * ["main"], // 0 399 | * { 400 | * "moduleId": (function(...){ 401 | * ... 402 | * }) 403 | * }, // 1. 404 | * [[0, 'runtime']] // 2. 405 | * ]) 406 | * 407 | * @param source 408 | * @param chunk 409 | */ 410 | private patchModule( 411 | source: ConcatSource, 412 | chunk: compilation.Chunk 413 | ): string | Source { 414 | // провееряем относится ли чанк к entry либ для шаринга 415 | const entries = this.sharedChunksAndEntriesAsArray.filter(([, entry]) => 416 | chunk.isInGroup(entry) 417 | ); 418 | 419 | if (!entries.length) { 420 | return source; 421 | } 422 | 423 | // Разделяем модули и их обертки, что бы не превращать в AST весь код. 424 | // Анализируем и модифицируем только обертки. 425 | const modules = []; 426 | let moduleWrappers = []; 427 | 428 | source.children.forEach((child) => { 429 | if (typeof child === 'string') { 430 | moduleWrappers.push(child); 431 | } else { 432 | modules.push(child); 433 | moduleWrappers.push(SharedLibraryWebpackPlugin.moduleSeparator); 434 | } 435 | }); 436 | 437 | const ast = jscodeshift(moduleWrappers.join('\n')) 438 | .find(jscodeshift.CallExpression) 439 | .at(0) // берем первый CallExpression, это как раз вызов пуш у window["webpackJsonp"] 440 | .replaceWith((path) => { 441 | const { value } = path; 442 | 443 | const [argument] = value.arguments as [jscodeshift.ArrayExpression]; 444 | 445 | // Элементы соответсвуют элементам массива, описанного в каменте к методу 446 | // eslint-disable-next-line prefer-const 447 | let [entryNames, modules, deps] = argument.elements as [ 448 | any, // первые два аргумента нам не интересны 449 | any, // по этому просто any 450 | jscodeshift.ArrayExpression 451 | ]; 452 | 453 | // Если deps нет, значит создаем массив сами. 454 | // Во сложенный массив обязательно добавляем первый элемент рывный null. 455 | // первый элемент - это id entry module. Его отсуствие означает, что 456 | // что чанк не содержит entry point 457 | if (!deps) { 458 | deps = jscodeshift.arrayExpression([ 459 | jscodeshift.arrayExpression([jscodeshift.identifier('null')]), 460 | ]); 461 | } 462 | 463 | const [initialDeps] = deps.elements as [jscodeshift.ArrayExpression]; 464 | 465 | // Вместо простого указания имени зависимости в entry мы создаем 466 | // функцию, которая вызывается на месте. 467 | // Цель - определить загружалась ли уже эта зависимость. Если загружалась 468 | // возвращается null, если нет - идентификатор зависимости 469 | const createCheckForDeferredModule = (ch: compilation.Chunk) => 470 | jscodeshift(`\ 471 | (function(id, name){ 472 | if(${this.globalObject}['${this.namespace}'] && ${this.globalObject}['${ 473 | this.namespace 474 | }'][name]){ 475 | return null; 476 | } 477 | return id; 478 | })(${typeof ch.id === 'string' ? `'${ch.id}'` : ch.id}, '${ch.name}')\ 479 | `) 480 | .find(jscodeshift.CallExpression) 481 | .paths()[0].value; 482 | 483 | // Строим новый массив из зивисимостей entry. 484 | // Примерно это будет на выходе. 485 | // 486 | // [[0, 'vendor'].concat([(function(){ 487 | // ... 488 | // })()].filter(m != null)]]) 489 | const args = jscodeshift.arrayExpression([ 490 | entryNames, 491 | modules, 492 | jscodeshift.arrayExpression([ 493 | jscodeshift.callExpression( 494 | jscodeshift.memberExpression( 495 | jscodeshift.arrayExpression(initialDeps.elements), 496 | jscodeshift.identifier('concat') 497 | ), 498 | [ 499 | jscodeshift.callExpression( 500 | jscodeshift.memberExpression( 501 | jscodeshift.arrayExpression([ 502 | ...entries.map(([chunk]) => 503 | createCheckForDeferredModule(chunk) 504 | ), 505 | ]), 506 | jscodeshift.identifier('filter') 507 | ), 508 | [ 509 | jscodeshift.functionExpression( 510 | null, 511 | [jscodeshift.identifier('entryName')], 512 | jscodeshift.blockStatement([ 513 | jscodeshift.returnStatement( 514 | jscodeshift.binaryExpression( 515 | '!=', 516 | jscodeshift.identifier('entryName'), 517 | jscodeshift.identifier('null') 518 | ) 519 | ), 520 | ]) 521 | ), 522 | ] 523 | ), 524 | ] 525 | ), 526 | ]), 527 | ]); 528 | 529 | return jscodeshift.callExpression(value.callee, [args]); 530 | }); 531 | 532 | moduleWrappers = ast 533 | .toSource() 534 | .split(SharedLibraryWebpackPlugin.moduleSeparator); 535 | 536 | // return the same structure as got 537 | return new ConcatSource( 538 | ...moduleWrappers.reduce((result, moduleWrapper, i) => { 539 | result.push(moduleWrapper); 540 | 541 | if (modules[i]) { 542 | result.push(modules[i]); 543 | } 544 | 545 | return result; 546 | }, []) 547 | ); 548 | } 549 | 550 | /** 551 | * Метод патчит функцию checkDeferredModules в runtime.js. 552 | * Функция проверяет загружены ли зависимости. 553 | * Если загружены все запускает entry module 554 | * 555 | * Мы учим ее качать наши расшаренные либы и игнорировать нулевой id для 556 | * entry module 557 | * @param source 558 | */ 559 | private patchRuntimeBootstrap(source: string | Source): string { 560 | source = enforceSourceToString(source); 561 | 562 | const ast = jscodeshift(source); 563 | 564 | const thisCodeLoadSharedLibs = this.sharedChunks 565 | .map((ch) => { 566 | return `\ 567 | if({'${ch.id}': true}[depId] === true && (!${this.globalObject}['${this.namespace}'] || !${this.globalObject}['${this.namespace}']['${ch.name}'])){ 568 | __webpack_require__.e('${ch.id}'); 569 | }`; 570 | }) 571 | .join(''); 572 | 573 | // ищем нудную функцию checkDeferredModules для патча 574 | const checkDeferredModulesFn = ast 575 | .find(jscodeshift.FunctionDeclaration) 576 | .filter((p) => isFnWithName('checkDeferredModules', p.value)); 577 | 578 | // учим качать расшаренные либы 579 | checkDeferredModulesFn 580 | .find(jscodeshift.IfStatement) 581 | .at(0) 582 | .replaceWith(() => { 583 | return `\ 584 | if(installedChunks[depId] !== 0){ 585 | fulfilled = false; 586 | 587 | ${thisCodeLoadSharedLibs} 588 | }`; 589 | }); 590 | 591 | // учим игнорить нулевой id у entry module 592 | checkDeferredModulesFn 593 | .find(jscodeshift.IfStatement) 594 | .at(-1) // последний if в функции 595 | .replaceWith((path) => { 596 | const { 597 | value: { test, consequent, alternate }, 598 | } = path; 599 | 600 | // патчим только само условие 601 | const newTest = jscodeshift( 602 | `${jscodeshift( 603 | test 604 | ).toSource()} && deferredModule.length && deferredModule[0] != null` 605 | ) 606 | .find(jscodeshift.LogicalExpression) 607 | .at(0) 608 | .paths()[0].value; 609 | 610 | return jscodeshift.ifStatement(newTest, consequent, alternate); 611 | }); 612 | 613 | return ast.toSource(); 614 | } 615 | 616 | /** 617 | * Выделение указанных либ в отдельные чанки 618 | */ 619 | private libraryToChunk() { 620 | // перебираем все точки входа, чанки и модули в поиске тех, 621 | // что нам нужно расшарить 622 | this.compilation.entrypoints.forEach((entry) => { 623 | const { chunks } = entry; 624 | 625 | for (const chunk of chunks) { 626 | for (const module of chunk.modulesIterable) { 627 | const librarySearchConfig = this.getLibrarySearchConfig(module); 628 | 629 | if (!librarySearchConfig) { 630 | continue; 631 | } 632 | 633 | const chunkName = [ 634 | librarySearchConfig.chunkName, 635 | librarySearchConfig.suffix, 636 | ...this.getDependencyNames(librarySearchConfig.deps), 637 | ] 638 | .filter((str) => !isNil(str)) 639 | .join(librarySearchConfig.separator); 640 | 641 | // если модуль c таким именем уже выделили переходим к следующему 642 | if (this.sharedChunks.some((ch) => ch.name === chunkName)) { 643 | continue; 644 | } 645 | 646 | // создаем чанк 647 | const newChunk: compilation.Chunk = this.compilation.addChunk( 648 | chunkName 649 | ); 650 | 651 | const addModuleToChunk = ( 652 | module: ModuleWithDeps, 653 | chunk: compilation.Chunk 654 | ) => { 655 | // удаляем модуль из других чанков 656 | module.chunksIterable.forEach((ch) => { 657 | module.removeChunk(ch); 658 | }); 659 | 660 | // добавляем модуль к новому чанку 661 | newChunk.addModule(module); 662 | 663 | // в зависимостях смотрим модули с тем же контекстом 664 | // добавляем их в тот же чанк 665 | module.dependencies 666 | .filter( 667 | (dep) => 668 | dep.module?.context.startsWith(module.context) && 669 | !this.getLibrarySearchConfig(dep.module) 670 | ) 671 | .forEach((dep) => addModuleToChunk(dep.module, chunk)); 672 | }; 673 | 674 | addModuleToChunk(module, newChunk); 675 | 676 | // Вырубаем tree shaking для нового чанка 677 | newChunk.modulesIterable.forEach((m: ModuleWithDeps) => { 678 | if (m.type.startsWith('javascript/')) { 679 | m.used = true; 680 | 681 | if ( 682 | Array.isArray(m.usedExports) && 683 | Array.isArray(librarySearchConfig.usedExports) 684 | ) { 685 | m.usedExports.push(...librarySearchConfig.usedExports); 686 | } else { 687 | m.usedExports = true; 688 | } 689 | 690 | m.buildMeta.providedExports = true; 691 | 692 | const id = !m.rawRequest 693 | ? null 694 | : m.rawRequest === module.rawRequest 695 | ? module.rawRequest 696 | : module.rawRequest + m.rawRequest; 697 | 698 | if (id) { 699 | // хэшируем шареные либы отдельно 700 | // что бы между приложениями в любом случае 701 | // хэши совпадали 702 | m.id = createUniqueHash(id); 703 | } 704 | } 705 | }); 706 | 707 | // хэшируем имя чанка в зависимости от версии и 708 | // внутренних импортов библиотеки 709 | const hashedChunkName = [...newChunk.modulesIterable] 710 | .map((m) => m.id) 711 | .filter(Boolean) 712 | .join(''); 713 | 714 | const hash = createHash('md4'); 715 | hash.update(hashedChunkName); 716 | newChunk.name = `${newChunk.name}.${hash.digest('hex').substr(0, 6)}`; 717 | 718 | // создаем одноименную группу 719 | const groupChunk: compilation.ChunkGroup = this.compilation.addChunkInGroup( 720 | newChunk.name 721 | ); 722 | 723 | // и привязываем его к одноименной группе 724 | (groupChunk as any).pushChunk(newChunk); 725 | 726 | // группу кидаем в дочерние точки входа 727 | // webpack в таком случае думает, что соответствующий модуль 728 | // заимпортирован через динамический import 729 | if (entry.addChild(groupChunk)) { 730 | (groupChunk as any).addParent(entry); 731 | } 732 | 733 | // и сохраняем ссылки на чанк и его точку входа 734 | // для патча кода обвязки модулей 735 | this.sharedChunksAndEntries.set(newChunk, entry); 736 | } 737 | } 738 | }); 739 | } 740 | 741 | private getDependencyNames( 742 | deps: SharedLibrarySearchConfig['deps'] 743 | ): string[] { 744 | return deps.reduce((result, name) => { 745 | return [ 746 | ...result, 747 | camelCase(name), 748 | compileSuffix( 749 | SharedLibraryWebpackPlugin.defaultSharedLibrarySearch.suffix, 750 | getPackageVersion(require(`${name}/package.json`).version) 751 | ), 752 | ]; 753 | }, []); 754 | } 755 | 756 | /** 757 | * Вычисление суффикса для модуля по его конфигу 758 | * 759 | * Если суффикс не задан пытаемся определить версию пакета по package.json и 760 | * используем как суффикс. 761 | * @param librarySearchConfig 762 | * @param module 763 | */ 764 | private getChunkNameSuffix( 765 | librarySearchConfig: SharedLibrarySearchConfig, 766 | module: { userRequest: string; rawRequest?: string } 767 | ): string | null { 768 | const { suffix } = librarySearchConfig; 769 | 770 | const { version } = 771 | findClosestPackageJsonWithVersion(parse(module.userRequest).dir) || {}; 772 | 773 | let templateData = {}; 774 | 775 | if (!version) { 776 | this.logger.warn(`Не найдена версия для пакета '${module.rawRequest}'`); 777 | } else { 778 | templateData = getPackageVersion(version); 779 | } 780 | 781 | return compileSuffix(suffix, templateData); 782 | } 783 | 784 | /** 785 | * Сопоставляем модуль и конфиги. 786 | * 787 | * Приоритетно ищем сопоставление сначала по name, потом по pattern 788 | * @param module 789 | */ 790 | private getLibrarySearchConfig(module: { 791 | userRequest: string; 792 | rawRequest?: string; 793 | }): SharedLibrarySearchConfig | null { 794 | if (!module.rawRequest) { 795 | return null; 796 | } 797 | 798 | let librarySearchConfig = this.libs 799 | .filter((lib) => !!lib.name) 800 | .find((lib) => module.rawRequest === lib.name); 801 | 802 | const chunkName = 803 | librarySearchConfig?.chunkName ?? camelCase(module.rawRequest); 804 | 805 | if (!librarySearchConfig) { 806 | librarySearchConfig = this.libs 807 | .filter((lib) => !!lib.pattern) 808 | .find((lib) => minimatch(module.rawRequest, lib.pattern)); 809 | } 810 | 811 | if (!librarySearchConfig) { 812 | return null; 813 | } 814 | 815 | const suffix = this.getChunkNameSuffix(librarySearchConfig, module); 816 | 817 | return { 818 | ...librarySearchConfig, 819 | chunkName, 820 | suffix, 821 | }; 822 | } 823 | } 824 | -------------------------------------------------------------------------------- /libs/shared-library-webpack-plugin/src/lib/utils.spec.ts: -------------------------------------------------------------------------------- 1 | import { 2 | createUniqueHash, 3 | enforceSourceToString, 4 | findClosestPackageJsonWithVersion, 5 | getTapFor, 6 | goUpFolders, 7 | isFnWithName, 8 | } from './utils'; 9 | import * as jscodeshift from 'jscodeshift'; 10 | import { ConcatSource } from 'webpack-sources'; 11 | import { Volume } from 'memfs'; 12 | import patchFs from 'fs-monkey/lib/patchFs'; 13 | import { ufs } from 'unionfs'; 14 | import * as fs from 'fs'; 15 | 16 | describe('getTapFor', () => { 17 | it('Если stage не передан, то по дефолту устанавливается 0', function () { 18 | expect(getTapFor('testName')).toEqual({ 19 | name: 'testName', 20 | stage: 0, 21 | }); 22 | }); 23 | 24 | it('Если stage передан, то устанавливается переданное значение', function () { 25 | expect(getTapFor('testName', 10)).toEqual({ 26 | name: 'testName', 27 | stage: 10, 28 | }); 29 | }); 30 | }); 31 | 32 | describe('isFnWithName', () => { 33 | it('Возвращает true, если нода - это функция с указанным именем', function () { 34 | jscodeshift(`function fnName(){}`) 35 | .find(jscodeshift.FunctionDeclaration) 36 | .forEach((path) => { 37 | expect(isFnWithName('fnName', path.value)).toBeTruthy(); 38 | }); 39 | }); 40 | 41 | it('Возвращает false, если нода - это функция с другим именем', function () { 42 | jscodeshift(`function otherFnName(){}`) 43 | .find(jscodeshift.FunctionDeclaration) 44 | .forEach((path) => { 45 | expect(isFnWithName('fnName', path.value)).toBeFalsy(); 46 | }); 47 | }); 48 | }); 49 | 50 | describe('enforceSourceToString', () => { 51 | it('Если передать строку, то вернется та же строка', function () { 52 | expect(enforceSourceToString('test text')).toEqual('test text'); 53 | }); 54 | 55 | it('Если передать Source, то вернется соответствующая строка', function () { 56 | const source = new ConcatSource('test text'); 57 | 58 | expect(enforceSourceToString(source)).toEqual('test text'); 59 | }); 60 | }); 61 | 62 | describe('goUpFolders', () => { 63 | it('Генератор продвигается вверх по пути до корня', function () { 64 | expect([...goUpFolders('/root/dir/dir2/dir3')]).toEqual([ 65 | '/root/dir/dir2/dir3', 66 | '/root/dir/dir2', 67 | '/root/dir', 68 | '/root', 69 | '/', 70 | ]); 71 | }); 72 | }); 73 | 74 | describe('findClosestPackageJsonWithVersion', () => { 75 | // eslint-disable-next-line 76 | let unpatch = () => {}; 77 | 78 | beforeAll(() => { 79 | const vol = Volume.fromJSON({ 80 | '/path/to/fake/package.json': '{"version":"0.0.0-version.0"}', 81 | '/path/to/fake/dir/dir1/package.json': '{}', 82 | 83 | '/anotherPath/to/fake/package.json': '{}', 84 | '/anotherPath/to/fake/dir/dir1/package.json': '{}', 85 | }); 86 | 87 | ufs.use(fs as any).use(vol as any); 88 | unpatch = patchFs(ufs); 89 | }); 90 | 91 | afterAll(() => { 92 | unpatch(); 93 | }); 94 | 95 | it('Находит первый package.json с версией', () => { 96 | const result = findClosestPackageJsonWithVersion('/path/to/fake/dir/dir1'); 97 | 98 | expect(result).toEqual({ version: '0.0.0-version.0' }); 99 | }); 100 | 101 | it('Если package.json с версией нет, то вернется null', () => { 102 | const result = findClosestPackageJsonWithVersion( 103 | '/anotherPath/to/fake/dir/dir1' 104 | ); 105 | 106 | expect(result).toEqual(null); 107 | }); 108 | }); 109 | 110 | describe('createUniqueHash', () => { 111 | it('Если', () => { 112 | const hash1 = createUniqueHash('string'); 113 | const hash2 = createUniqueHash('string'); 114 | 115 | expect(hash1).not.toEqual(hash2); 116 | }); 117 | }); 118 | -------------------------------------------------------------------------------- /libs/shared-library-webpack-plugin/src/lib/utils.ts: -------------------------------------------------------------------------------- 1 | import { Tap } from 'tapable'; 2 | import { Source } from 'webpack-sources'; 3 | import { join, resolve } from 'path'; 4 | import { existsSync, readFileSync } from 'fs'; 5 | import { FunctionDeclaration } from 'jscodeshift'; 6 | import * as semver from 'semver'; 7 | import { createHash } from 'crypto'; 8 | import { template } from 'lodash'; 9 | 10 | /** 11 | * [Конфиг хука]{@see Tap} с приоритетом 12 | * 13 | * Хуки из либы [tapable]{@link https://github.com/webpack/tapable} (ее узает 14 | * webpack под капотом) могут принимать параметр stage, который определяет 15 | * очередность запуска колбэка. Чем выше число - тем позднее будет выполнен колбэк 16 | * @param name 17 | * @param stage 18 | */ 19 | export function getTapFor(name: string, stage?: number): Tap { 20 | return { 21 | name, 22 | stage: stage ?? 0, 23 | } as Tap; 24 | } 25 | 26 | /** 27 | * Вернет true, если нода функции с указанным именем 28 | * {@see FunctionDeclaration} 29 | * @param name 30 | * @param n 31 | */ 32 | export function isFnWithName(name: string, n: FunctionDeclaration): boolean { 33 | return n && n.id && n.id.name === name; 34 | } 35 | 36 | /** 37 | * Принудительно приводим к строке 38 | * @param source 39 | */ 40 | export function enforceSourceToString(source: string | Source): string { 41 | return typeof source === 'string' ? source : source.source(); 42 | } 43 | 44 | /** 45 | * Двигаемся вверх по дереву папок, либо до cwd, либо до корня 46 | * @param root 47 | */ 48 | export function* goUpFolders(root: string): Generator { 49 | yield root; 50 | 51 | while (!root.match(/^(\w:\\|\/)$/) && root !== process.cwd()) { 52 | root = resolve(root, '..'); 53 | yield root; 54 | } 55 | } 56 | 57 | /** 58 | * Возвращаем первый попавшийся package.json с version 59 | * @param root 60 | */ 61 | export function findClosestPackageJsonWithVersion( 62 | root: string 63 | ): null | { version: string } { 64 | for (const path of goUpFolders(root)) { 65 | const file = join(path, 'package.json'); 66 | 67 | if (existsSync(path)) { 68 | try { 69 | const pack = JSON.parse(readFileSync(file).toString()); 70 | 71 | if (pack?.version) { 72 | return pack; 73 | } 74 | } catch (e) {} //eslint-disable-line 75 | } 76 | } 77 | 78 | return null; 79 | } 80 | 81 | export interface PackageVersion { 82 | major: number; 83 | minor: number; 84 | patch: number; 85 | prerelease?: string; 86 | } 87 | 88 | export function getPackageVersion(version: string): PackageVersion | null { 89 | const { major, minor, prerelease, patch } = semver.parse(version); 90 | 91 | return { 92 | major, 93 | minor, 94 | prerelease: prerelease.length ? `-${prerelease.join('.')}` : '', 95 | patch, 96 | }; 97 | } 98 | 99 | export function compileSuffix( 100 | suffix: string, 101 | data: Partial 102 | ): string { 103 | const compiled = template(suffix); 104 | 105 | return compiled(data); 106 | } 107 | 108 | const usedIds = new Set(); 109 | 110 | export function createUniqueHash(str: string): string { 111 | const hash = createHash('md4'); 112 | hash.update(str); 113 | const hashId = hash.digest('hex'); 114 | let len = 4; 115 | while (usedIds.has(hashId.substr(0, len))) len++; 116 | const generatedHash = hashId.substr(0, len); 117 | 118 | usedIds.add(generatedHash); 119 | 120 | return generatedHash; 121 | } 122 | -------------------------------------------------------------------------------- /libs/shared-library-webpack-plugin/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../../tsconfig.json", 3 | "compilerOptions": { 4 | "types": ["node", "jest"] 5 | }, 6 | "include": ["**/*.ts"] 7 | } 8 | -------------------------------------------------------------------------------- /libs/shared-library-webpack-plugin/tsconfig.lib.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "module": "commonjs", 5 | "outDir": "../../dist/out-tsc", 6 | "declaration": true, 7 | "rootDir": "./src", 8 | "types": ["node"] 9 | }, 10 | "exclude": ["**/*.spec.ts"], 11 | "include": ["**/*.ts"] 12 | } 13 | -------------------------------------------------------------------------------- /libs/shared-library-webpack-plugin/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../../dist/out-tsc", 5 | "module": "commonjs", 6 | "types": ["jest", "node"] 7 | }, 8 | "include": [ 9 | "**/*.spec.ts", 10 | "**/*.spec.tsx", 11 | "**/*.spec.js", 12 | "**/*.spec.jsx", 13 | "**/*.d.ts" 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /license.md: -------------------------------------------------------------------------------- 1 | # License 2 | 3 | Version 2.0, January 2004 4 | 5 | Apache License 6 | 7 | [http://www.apache.org/licenses/](http://www.apache.org/licenses/) 8 | 9 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 10 | 11 | 1. Definitions. 12 | 13 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. 14 | 15 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 16 | 17 | "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means \(i\) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or \(ii\) ownership of fifty percent \(50%\) or more of the outstanding shares, or \(iii\) beneficial ownership of such entity. 18 | 19 | "You" \(or "Your"\) shall mean an individual or Legal Entity exercising permissions granted by this License. 20 | 21 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 22 | 23 | "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. 24 | 25 | "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work \(an example is provided in the Appendix below\). 26 | 27 | "Derivative Works" shall mean any work, whether in Source or Object form, that is based on \(or derived from\) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link \(or bind by name\) to the interfaces of, the Work and Derivative Works thereof. 28 | 29 | "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." 30 | 31 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 32 | 33 | 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 34 | 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable \(except as stated in this section\) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution\(s\) alone or by combination of their Contribution\(s\) with the Work to which such Contribution\(s\) was submitted. If You institute patent litigation against any entity \(including a cross-claim or counterclaim in a lawsuit\) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 35 | 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: 36 | 37 | \(a\) You must give any other recipients of the Work or Derivative Works a copy of this License; and 38 | 39 | \(b\) You must cause any modified files to carry prominent notices stating that You changed the files; and 40 | 41 | \(c\) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and 42 | 43 | \(d\) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. 44 | 45 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 46 | 47 | 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 48 | 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 49 | 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work \(and each Contributor provides its Contributions\) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 50 | 8. Limitation of Liability. In no event and under no legal theory, whether in tort \(including negligence\), contract, or otherwise, unless required by applicable law \(such as deliberate and grossly negligent acts\) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work \(including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses\), even if such Contributor has been advised of the possibility of such damages. 51 | 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. 52 | 53 | END OF TERMS AND CONDITIONS 54 | 55 | Copyright 2020 Tinkoff Bank 56 | 57 | Licensed under the Apache License, Version 2.0 \(the "License"\); you may not use this file except in compliance with the License. You may obtain a copy of the License at 58 | 59 | [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) 60 | 61 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 62 | 63 | -------------------------------------------------------------------------------- /nx.json: -------------------------------------------------------------------------------- 1 | { 2 | "npmScope": "shared-library-webpack-plugin", 3 | "implicitDependencies": { 4 | "workspace.json": "*", 5 | "package.json": { 6 | "dependencies": "*", 7 | "devDependencies": "*" 8 | }, 9 | "tsconfig.json": "*", 10 | "tslint.json": "*", 11 | "nx.json": "*" 12 | }, 13 | "tasksRunnerOptions": { 14 | "default": { 15 | "runner": "@nrwl/workspace/tasks-runners/default", 16 | "options": { 17 | "cacheableOperations": [] 18 | } 19 | } 20 | }, 21 | "projects": { 22 | "sandbox": { 23 | "tags": [] 24 | }, 25 | "shared-library-webpack-plugin": { 26 | "tags": [] 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "shared-library-webpack-plugin", 3 | "version": "0.0.0-development.0", 4 | "private": true, 5 | "license": "Apache-2.0", 6 | "scripts": { 7 | "affected": "nx affected", 8 | "affected:apps": "nx affected:apps", 9 | "affected:build": "nx affected:build", 10 | "affected:dep-graph": "nx affected:dep-graph", 11 | "affected:e2e": "nx affected:e2e", 12 | "affected:libs": "nx affected:libs", 13 | "affected:lint": "nx affected:lint", 14 | "affected:test": "nx affected:test", 15 | "build": "nx build", 16 | "dep-graph": "nx dep-graph", 17 | "e2e": "nx e2e", 18 | "format": "nx format:write", 19 | "format:check": "nx format:check", 20 | "format:write": "nx format:write", 21 | "help": "nx help", 22 | "lint": "nx workspace-lint && nx lint", 23 | "nx": "nx", 24 | "release": "semantic-release", 25 | "start": "nx serve", 26 | "test": "nx test", 27 | "update": "nx migrate latest", 28 | "workspace-schematic": "nx workspace-schematic" 29 | }, 30 | "husky": { 31 | "hooks": { 32 | "pre-commit": "lint-staged" 33 | } 34 | }, 35 | "lint-staged": { 36 | "*.ts": "eslint", 37 | "*.{js,ts,html,md,less,json}": [ 38 | "prettier --write", 39 | "git add" 40 | ] 41 | }, 42 | "dependencies": { 43 | "document-register-element": "1.13.1" 44 | }, 45 | "devDependencies": { 46 | "@angular/common": "^10.0.11", 47 | "@angular/core": "^10.0.11", 48 | "@ng-builders/build": "^1.1.0", 49 | "@nrwl/eslint-plugin-nx": "9.3.0", 50 | "@nrwl/jest": "9.3.0", 51 | "@nrwl/node": "^9.3.0", 52 | "@nrwl/web": "9.3.0", 53 | "@nrwl/workspace": "9.3.0", 54 | "@semantic-release/commit-analyzer": "^8.0.1", 55 | "@semantic-release/github": "^7.0.7", 56 | "@semantic-release/npm": "^7.0.5", 57 | "@semantic-release/release-notes-generator": "^9.0.1", 58 | "@types/jest": "25.1.4", 59 | "@types/jscodeshift": "^0.7.1", 60 | "@types/lodash": "^4.14.171", 61 | "@types/node": "~8.9.4", 62 | "@types/puppeteer": "^2.1.0", 63 | "@types/semver": "^7.3.7", 64 | "@types/webpack": "^4.41.13", 65 | "@typescript-eslint/eslint-plugin": "2.19.2", 66 | "@typescript-eslint/parser": "2.19.2", 67 | "@webcomponents/custom-elements": "1.3.2", 68 | "dotenv": "6.2.0", 69 | "eslint": "6.8.0", 70 | "eslint-config-prettier": "6.0.0", 71 | "fs-monkey": "^1.0.1", 72 | "husky": "^4.2.5", 73 | "jest": "25.2.3", 74 | "jscodeshift": "^0.9.0", 75 | "lint-staged": "^10.2.6", 76 | "lodash": "^4.17.15", 77 | "memfs": "^3.1.3", 78 | "minimatch": "^3.0.4", 79 | "prettier": "2.0.4", 80 | "puppeteer": "^3.1.0", 81 | "rxjs": "^6.5.5", 82 | "semantic-release": "^17.0.7", 83 | "ts-jest": "25.2.1", 84 | "ts-node": "~7.0.0", 85 | "tslint": "~6.0.0", 86 | "typescript": "~3.8.3", 87 | "unionfs": "^4.4.0", 88 | "uuid": "^8.1.0", 89 | "webpack": "^4.43.0", 90 | "zone.js": "^0.10.3" 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /tools/schematics/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tinkoff/shared-library-webpack-plugin/8c6bd84e020858886eaadd0cdcc9e8bb8b017b9b/tools/schematics/.gitkeep -------------------------------------------------------------------------------- /tools/tsconfig.tools.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../dist/out-tsc/tools", 5 | "rootDir": ".", 6 | "module": "commonjs", 7 | "target": "es5", 8 | "types": ["node"] 9 | }, 10 | "include": ["**/*.ts"] 11 | } 12 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "rootDir": ".", 5 | "sourceMap": true, 6 | "declaration": false, 7 | "moduleResolution": "node", 8 | "emitDecoratorMetadata": true, 9 | "experimentalDecorators": true, 10 | "importHelpers": true, 11 | "target": "es2015", 12 | "module": "commonjs", 13 | "typeRoots": ["node_modules/@types"], 14 | "lib": ["es2017", "dom"], 15 | "skipLibCheck": true, 16 | "skipDefaultLibCheck": true, 17 | "baseUrl": "." 18 | }, 19 | "exclude": ["node_modules", "tmp"] 20 | } 21 | -------------------------------------------------------------------------------- /workspace.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": 1, 3 | "projects": { 4 | "sandbox": { 5 | "root": "apps/sandbox", 6 | "sourceRoot": "apps/sandbox/src", 7 | "projectType": "application", 8 | "schematics": {}, 9 | "architect": { 10 | "build": { 11 | "builder": "@nrwl/web:build", 12 | "options": { 13 | "webpackConfig": "apps/sandbox/webpack.config.js", 14 | "outputPath": "dist/apps/sandbox", 15 | "index": "apps/sandbox/src/index.html", 16 | "main": "apps/sandbox/src/main.ts", 17 | "tsConfig": "apps/sandbox/tsconfig.app.json", 18 | "assets": [ 19 | "apps/sandbox/src/favicon.ico", 20 | "apps/sandbox/src/assets" 21 | ], 22 | "styles": ["apps/sandbox/src/styles.scss"], 23 | "scripts": [], 24 | "vendorChunk": false 25 | }, 26 | "configurations": { 27 | "production": { 28 | "fileReplacements": [ 29 | { 30 | "replace": "apps/sandbox/src/environments/environment.ts", 31 | "with": "apps/sandbox/src/environments/environment.prod.ts" 32 | } 33 | ], 34 | "optimization": true, 35 | "outputHashing": "all", 36 | "sourceMap": false, 37 | "extractCss": true, 38 | "namedChunks": false, 39 | "extractLicenses": true, 40 | "vendorChunk": false, 41 | "budgets": [ 42 | { 43 | "type": "initial", 44 | "maximumWarning": "2mb", 45 | "maximumError": "5mb" 46 | } 47 | ] 48 | } 49 | } 50 | }, 51 | "serve": { 52 | "builder": "@nrwl/web:dev-server", 53 | "options": { 54 | "buildTarget": "sandbox:build" 55 | }, 56 | "configurations": { 57 | "production": { 58 | "buildTarget": "sandbox:build:production" 59 | } 60 | } 61 | }, 62 | "lint": { 63 | "builder": "@nrwl/linter:lint", 64 | "options": { 65 | "linter": "eslint", 66 | "config": "apps/sandbox/.eslintrc", 67 | "tsConfig": [ 68 | "apps/sandbox/tsconfig.app.json", 69 | "apps/sandbox/tsconfig.spec.json" 70 | ], 71 | "exclude": ["**/node_modules/**", "!apps/sandbox/**"] 72 | } 73 | }, 74 | "test": { 75 | "builder": "@nrwl/jest:jest", 76 | "options": { 77 | "jestConfig": "apps/sandbox/jest.config.js", 78 | "tsConfig": "apps/sandbox/tsconfig.spec.json", 79 | "passWithNoTests": true, 80 | "setupFile": "apps/sandbox/src/test-setup.ts" 81 | } 82 | } 83 | } 84 | }, 85 | "shared-library-webpack-plugin": { 86 | "root": "libs/shared-library-webpack-plugin", 87 | "sourceRoot": "libs/shared-library-webpack-plugin/src", 88 | "projectType": "library", 89 | "schematics": {}, 90 | "architect": { 91 | "lint": { 92 | "builder": "@nrwl/linter:lint", 93 | "options": { 94 | "linter": "eslint", 95 | "config": "libs/shared-library-webpack-plugin/.eslintrc", 96 | "tsConfig": [ 97 | "libs/shared-library-webpack-plugin/tsconfig.lib.json", 98 | "libs/shared-library-webpack-plugin/tsconfig.spec.json" 99 | ], 100 | "exclude": [ 101 | "**/node_modules/**", 102 | "!libs/shared-library-webpack-plugin/**" 103 | ] 104 | } 105 | }, 106 | "test": { 107 | "builder": "@ng-builders/build:stepper", 108 | "options": { 109 | "targets": { 110 | "jest": { 111 | "target": "shared-library-webpack-plugin:jest", 112 | "deps": ["server"] 113 | }, 114 | "server": { 115 | "target": "sandbox:serve", 116 | "watch": true 117 | }, 118 | "build": { 119 | "target": "shared-library-webpack-plugin:build" 120 | } 121 | }, 122 | "steps": ["build", "jest"] 123 | } 124 | }, 125 | "jest": { 126 | "builder": "@nrwl/jest:jest", 127 | "options": { 128 | "jestConfig": "libs/shared-library-webpack-plugin/jest.config.js", 129 | "tsConfig": "libs/shared-library-webpack-plugin/tsconfig.spec.json" 130 | } 131 | }, 132 | "build": { 133 | "builder": "@nrwl/node:package", 134 | "options": { 135 | "outputPath": "dist/libs/shared-library-webpack-plugin", 136 | "tsConfig": "libs/shared-library-webpack-plugin/tsconfig.lib.json", 137 | "packageJson": "libs/shared-library-webpack-plugin/package.json", 138 | "main": "libs/shared-library-webpack-plugin/src/index.ts", 139 | "assets": [ 140 | "README.md", 141 | "SUMMARY.md", 142 | "license.md", 143 | "code_of_conduct.md", 144 | "contributing.md", 145 | { 146 | "glob": "**/*.md", 147 | "input": "docs", 148 | "output": "docs" 149 | } 150 | ] 151 | } 152 | } 153 | } 154 | } 155 | }, 156 | "cli": { 157 | "defaultCollection": "@nrwl/node" 158 | }, 159 | "schematics": { 160 | "@nrwl/workspace": { 161 | "library": { 162 | "linter": "eslint" 163 | } 164 | }, 165 | "@nrwl/cypress": { 166 | "cypress-project": { 167 | "linter": "eslint" 168 | } 169 | }, 170 | "@nrwl/react": { 171 | "application": { 172 | "linter": "eslint" 173 | }, 174 | "library": { 175 | "linter": "eslint" 176 | }, 177 | "storybook-configuration": { 178 | "linter": "eslint" 179 | } 180 | }, 181 | "@nrwl/next": { 182 | "application": { 183 | "linter": "eslint" 184 | } 185 | }, 186 | "@nrwl/web": { 187 | "application": { 188 | "linter": "eslint" 189 | } 190 | }, 191 | "@nrwl/node": { 192 | "application": { 193 | "linter": "eslint" 194 | }, 195 | "library": { 196 | "linter": "eslint" 197 | } 198 | }, 199 | "@nrwl/nx-plugin": { 200 | "plugin": { 201 | "linter": "eslint" 202 | } 203 | }, 204 | "@nrwl/nest": { 205 | "application": { 206 | "linter": "eslint" 207 | } 208 | }, 209 | "@nrwl/express": { 210 | "application": { 211 | "linter": "eslint" 212 | }, 213 | "library": { 214 | "linter": "eslint" 215 | } 216 | } 217 | }, 218 | "defaultProject": "shared-library-webpack-plugin" 219 | } 220 | --------------------------------------------------------------------------------