├── .changeset
├── README.md
├── big-pugs-bake.md
└── config.json
├── .editorconfig
├── .eslintignore
├── .eslintrc.yaml
├── .github
├── FUNDING.yml
├── ISSUE_TEMPLATE
│ └── config.yml
└── workflows
│ ├── ci.yml
│ └── release.yml
├── .gitignore
├── .npmrc
├── .prettierrc.yaml
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── jsconfig.json
├── mount-tmp-playground.sh
├── package.json
├── packages
└── svelte-hmr
│ ├── CHANGELOG.md
│ ├── LICENSE
│ ├── README.md
│ ├── index.js
│ ├── lib
│ ├── css-only.js
│ └── make-hot.js
│ ├── package.json
│ └── runtime
│ ├── hot-api-esm.js
│ ├── hot-api.js
│ ├── index.js
│ ├── overlay.js
│ ├── proxy-adapter-dom.js
│ ├── proxy.js
│ ├── svelte-hooks.js
│ └── svelte-native
│ ├── patch-page-show-modal.js
│ └── proxy-adapter-native.js
├── playground
├── $test
│ ├── config.js
│ ├── helpers.js
│ ├── hmr-context.js
│ ├── hmr-macro.js
│ ├── index.js
│ └── util.js
├── basic
│ ├── $set.spec.js
│ ├── action.spec.js
│ ├── basic.spec.js
│ ├── bindings.spec.js
│ ├── bug.spec.js
│ ├── callbacks.spec.js
│ ├── context.spec.js
│ ├── empty-component.spec.js
│ ├── index.html
│ ├── keyed-list.spec.js
│ ├── lifecycle.spec.js
│ ├── local-state-preserveLocalStateKey.spec.js
│ ├── local-state.spec.js
│ ├── module-context.spec.js
│ ├── option-accessors.spec.js
│ ├── outro.spec.js
│ ├── package.json
│ ├── props.spec.js
│ ├── reactive-statements.spec.js
│ ├── revival.spec.js
│ ├── simultaneous-update-parent-child.spec.js
│ ├── slots.spec.js
│ ├── src
│ │ ├── App.svelte
│ │ └── main.js
│ ├── stores.spec.js
│ ├── style.spec.js
│ ├── svelte-component.spec.js
│ ├── transform-regex.spec.js
│ └── vite.config.js
├── jsconfig.json
├── package.json
├── vitest.config.js
├── vitestGlobalSetup.js
└── vitestSetup.js
├── pnpm-lock.yaml
└── pnpm-workspace.yaml
/.changeset/README.md:
--------------------------------------------------------------------------------
1 | # Changesets
2 |
3 | Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works
4 | with multi-package repos, or single-package repos to help you version and publish your code. You can
5 | find the full documentation for it [in our repository](https://github.com/changesets/changesets)
6 |
7 | We have a quick list of common questions to get you started engaging with this project in
8 | [our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md)
9 |
--------------------------------------------------------------------------------
/.changeset/big-pugs-bake.md:
--------------------------------------------------------------------------------
1 | ---
2 | 'svelte-hmr': minor
3 | ---
4 |
5 | Rewrite tests to get rid of old vulnerable (dev) dependencies, and update CI setup
6 |
--------------------------------------------------------------------------------
/.changeset/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://unpkg.com/@changesets/config@1.6.0/schema.json",
3 | "changelog": ["@svitejs/changesets-changelog-github-compact", { "repo": "sveltejs/svelte-hmr" }],
4 | "commit": false,
5 | "linked": [],
6 | "access": "public",
7 | "baseBranch": "master",
8 | "updateInternalDependencies": "patch"
9 | }
10 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | end_of_line = lf
5 | insert_final_newline = true
6 | indent_style = space
7 | indent_size = 2
8 | charset = utf-8
9 | trim_trailing_whitespace = true
10 |
--------------------------------------------------------------------------------
/.eslintignore:
--------------------------------------------------------------------------------
1 | *.ts
2 |
--------------------------------------------------------------------------------
/.eslintrc.yaml:
--------------------------------------------------------------------------------
1 | parserOptions:
2 | sourceType: module
3 | ecmaVersion: latest
4 |
5 | # overrides:
6 | # - files:
7 | # - "packages/svelte-hmr/index.js"
8 | # - "packages/svelte-hmr/lib/**/*"
9 | # - "**/rollup.config.js"
10 | # env:
11 | # node: true
12 |
13 | env:
14 | node: true
15 | # es2022: true
16 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | open_collective: svelte
2 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/config.yml:
--------------------------------------------------------------------------------
1 | blank_issues_enabled: true
2 | contact_links:
3 | - name: Svelte Discord
4 | url: https://svelte.dev/chat
5 | about: If you want to chat, join our discord.
6 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | # build and test
2 | name: CI
3 |
4 | on:
5 | push:
6 | branches:
7 | - master
8 | pull_request:
9 | branches:
10 | - master
11 |
12 | env:
13 | # we call `pnpm playwright install` instead
14 | PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: '1'
15 |
16 | jobs:
17 | # "checks" job runs on linux + 16 only and checks that install, build, lint and audit work
18 | # it also primes the pnpm store cache for linux, important for downstream tests
19 | checks:
20 | timeout-minutes: 5
21 | runs-on: ${{ matrix.os }}
22 | strategy:
23 | matrix:
24 | # pseudo-matrix for convenience, NEVER use more than a single combination
25 | node: [16]
26 | os: [ubuntu-latest]
27 | outputs:
28 | build_successful: ${{ steps.build.outcome == 'success' }}
29 | steps:
30 | - uses: actions/checkout@v4
31 | - uses: pnpm/action-setup@v4
32 | - uses: actions/setup-node@v4
33 | with:
34 | node-version: ${{ matrix.node }}
35 | cache: 'pnpm'
36 | - name: install
37 | run: pnpm install --frozen-lockfile --prefer-offline
38 | # reactivate this when there is a build step
39 | # - name: build
40 | # id: build
41 | # run: pnpm run build
42 | - name: lint
43 | if: (${{ success() }} || ${{ failure() }})
44 | run: pnpm run lint
45 | - name: audit
46 | if: (${{ success() }} || ${{ failure() }})
47 | run: pnpm audit
48 |
49 | # this is the test matrix
50 | # it is skipped if the build step of the checks job wasn't successful (still runs if lint or audit fail)
51 | test:
52 | needs: checks
53 | if: (${{ success() }} || ${{ failure() }}) && (${{ needs.checks.output.build_successful }})
54 | timeout-minutes: 10
55 | runs-on: ${{ matrix.os }}
56 | strategy:
57 | fail-fast: false
58 | matrix:
59 | os: [ ubuntu-latest, macos-latest ]
60 | node: [ 16, 18, 20, 22 ]
61 | steps:
62 | - uses: actions/checkout@v4
63 | - uses: pnpm/action-setup@v4
64 | - uses: actions/setup-node@v4
65 | with:
66 | node-version: ${{ matrix.node }}
67 | cache: 'pnpm'
68 | - name: use svelte 3
69 | if: matrix.svelte == 3
70 | run: |
71 | tmppkg="$(jq '.devDependencies.svelte = "^3.59.2"' package.json)" && echo -E "${tmppkg}" > package.json && tmppkg=""
72 | - name: install
73 | if: matrix.node != 14 && matrix.svelte != 3
74 | run: pnpm install --frozen-lockfile --prefer-offline
75 | - name: install for node14 or svelte3
76 | if: matrix.node == 14 || matrix.svelte == 3
77 | run: pnpm install --no-frozen-lockfile --prefer-offline
78 | - name: install playwright chromium
79 | run: cd playground && pnpm playwright install chromium
80 | - name: run tests
81 | run: pnpm test
82 |
--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | name: Release
2 |
3 | on:
4 | push:
5 | branches:
6 | - master
7 |
8 | jobs:
9 | release:
10 | # prevents this action from running on forks
11 | if: github.repository == 'sveltejs/svelte-hmr'
12 | name: Release
13 | runs-on: ${{ matrix.os }}
14 | strategy:
15 | matrix:
16 | # pseudo-matrix for convenience, NEVER use more than a single combination
17 | node: [20]
18 | os: [ubuntu-latest]
19 | steps:
20 | - name: checkout
21 | uses: actions/checkout@v4
22 | with:
23 | # This makes Actions fetch all Git history so that Changesets can generate changelogs with the correct commits
24 | fetch-depth: 0
25 | - uses: actions/setup-node@v4
26 | with:
27 | node-version: ${{ matrix.node }}
28 | - name: install pnpm
29 | shell: bash
30 | run: |
31 | PNPM_VER=$(jq -r '.packageManager | if .[0:5] == "pnpm@" then .[5:] else "packageManager in package.json does not start with pnpm@\n" | halt_error(1) end' package.json)
32 | echo installing pnpm version $PNPM_VER
33 | npm i -g pnpm@$PNPM_VER
34 | - uses: actions/setup-node@v4
35 | with:
36 | node-version: ${{ matrix.node }}
37 | cache: 'pnpm'
38 | cache-dependency-path: '**/pnpm-lock.yaml'
39 | - name: install
40 | run: pnpm install --frozen-lockfile --prefer-offline
41 |
42 | - name: Creating .npmrc
43 | run: |
44 | cat << EOF > "$HOME/.npmrc"
45 | //registry.npmjs.org/:_authToken=$NPM_TOKEN
46 | EOF
47 | env:
48 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
49 | - name: Create Release Pull Request or Publish to npm
50 | id: changesets
51 | uses: changesets/action@v1
52 | with:
53 | # This expects you to have a script called release which does a build for your packages and calls changeset publish
54 | publish: pnpm release
55 | env:
56 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
57 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
58 |
59 | # TODO alert discord
60 | # - name: Send a Slack notification if a publish happens
61 | # if: steps.changesets.outputs.published == 'true'
62 | # # You can do something when a publish happens.
63 | # run: my-slack-bot send-notification --message "A new version of ${GITHUB_REPOSITORY} was published!"
64 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # logs and temp
2 | *.log
3 | **/*.log
4 | *.cpuprofile
5 | **/*.cpuprofile
6 | temp
7 | **/temp
8 | *.tmp
9 | **/*.tmp
10 |
11 | # build and dist
12 | build
13 | **/build
14 | dist
15 | **/dist
16 |
17 | # env and local
18 | *.local
19 | **/*.local
20 | .env
21 | **/.env
22 |
23 | #node_modules and pnpm
24 | node_modules
25 | **/node_modules
26 | # only workspace root has a lock
27 | pnpm-lock.yaml
28 | !/pnpm-lock.yaml
29 | .pnpm-store
30 | **/.pnpm-store
31 |
32 | #ide
33 | .idea
34 | **/.idea
35 | .vscode
36 | **/.vscode
37 |
38 | # macos
39 | .DS_Store
40 | ._.DS_Store
41 | **/.DS_Store
42 | **/._.DS_Store
43 |
44 | # misc
45 | *.bak.*
46 | *.bak
47 | *.orig
48 |
49 | # temporary playground files
50 | /playground-*/
51 |
--------------------------------------------------------------------------------
/.npmrc:
--------------------------------------------------------------------------------
1 | auto-install-peers=false
2 |
--------------------------------------------------------------------------------
/.prettierrc.yaml:
--------------------------------------------------------------------------------
1 | plugins:
2 | - prettier-plugin-jsdoc
3 |
4 | semi: false
5 | singleQuote: true
6 | trailingComma: es5
7 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing to svelte-hmr
2 |
3 | svelte-hmr provides low-level tooling to enable hot module reloading with svelte
4 |
5 | - [Svelte](https://svelte.dev/) is a new way to build web applications. It's a compiler that takes your declarative components and converts them into efficient JavaScript that surgically updates the DOM.
6 |
7 | The [Open Source Guides](https://opensource.guide/) website has a collection of resources for individuals, communities, and companies. These resources help people who want to learn how to run and contribute to open source projects. Contributors and people new to open source alike will find the following guides especially useful:
8 |
9 | - [How to Contribute to Open Source](https://opensource.guide/how-to-contribute/)
10 | - [Building Welcoming Communities](https://opensource.guide/building-community/)
11 |
12 | ## Get involved
13 |
14 | There are many ways to contribute to svelte-hmr, and many of them do not involve writing any code. Here's a few ideas to get started:
15 |
16 | - Simply start using svelte-hmr. Does everything work as expected? If not, we're always looking for improvements. Let us know by [opening an issue](#reporting-new-issues).
17 | - Look through the [open issues](https://github.com/rixo/svelte-hmr/issues). Provide workarounds, ask for clarification, or suggest labels. Help [triage issues](#triaging-issues-and-pull-requests).
18 | - If you find an issue you would like to fix, [open a pull request](#your-first-pull-request).
19 | - Read through our [documentation](https://github.com/rixo/svelte-hmr/tree/main/docs). If you find anything that is confusing or can be improved, open a pull request.
20 | - Take a look at the [features requested](https://github.com/rixo/svelte-hmr/labels/enhancement) by others in the community and consider opening a pull request if you see something you want to work on.
21 |
22 | Contributions are very welcome. If you think you need help planning your contribution, please ping us on Discord at [svelte.dev/chat](https://svelte.dev/chat) and let us know you are looking for a bit of help.
23 |
24 | ### Triaging issues and pull requests
25 |
26 | One great way you can contribute to the project without writing any code is to help triage issues and pull requests as they come in.
27 |
28 | - Ask for more information if you believe the issue does not provide all the details required to solve it.
29 | - Suggest [labels](https://github.com/rixo/svelte-hmr/labels) that can help categorize issues.
30 | - Flag issues that are stale or that should be closed.
31 | - Ask for test plans and review code.
32 |
33 | ## Bugs
34 |
35 | We use [GitHub issues](https://github.com/rixo/svelte-hmr/issues) for our public bugs. If you would like to report a problem, take a look around and see if someone already opened an issue about it. If you are certain this is a new unreported bug, you can submit a [bug report](#reporting-new-issues).
36 |
37 | If you have questions about using svelte-hmr, contact us on Discord at [svelte.dev/chat](https://svelte.dev/chat), and we will do our best to answer your questions.
38 |
39 | If you see anything you'd like to be implemented, create a [feature request issue](https://github.com/rixo/svelte-hmr/issues/new?template=feature_request.md)
40 |
41 | ## Reporting new issues
42 |
43 | When [opening a new issue](https://github.com/sveltejs/svelte/issues/new/new?template=bug_report.md), always make sure to fill out the issue template. **This step is very important!** Not doing so may result in your issue not being managed in a timely fashion. Don't take this personally if this happens, and feel free to open a new issue once you've gathered all the information required by the template.
44 |
45 | - **One issue, one bug:** Please report a single bug per issue.
46 | - **Provide reproduction steps:** List all the steps necessary to reproduce the issue. The person reading your bug report should be able to follow these steps to reproduce your issue with minimal effort.
47 |
48 | ## Installation
49 |
50 | 1. This project uses [pnpm](https://pnpm.js.org/en/). Install it with `npm i -g pnpm`
51 | 1. After cloning the repo run `pnpm install` to install dependencies
52 |
53 | ## Pull requests
54 |
55 | ### Your first pull request
56 |
57 | So you have decided to contribute code back to upstream by opening a pull request. You've invested a good chunk of time, and we appreciate it. We will do our best to work with you and get the PR looked at.
58 |
59 | Working on your first Pull Request? You can learn how from this free video series:
60 |
61 | [**How to Contribute to an Open Source Project on GitHub**](https://egghead.io/courses/how-to-contribute-to-an-open-source-project-on-github)
62 |
63 | ### Proposing a change
64 |
65 | If you would like to request a new feature or enhancement but are not yet thinking about opening a pull request, you can also file an issue with [feature template](https://github.com/rixo/svelte-hmr/issues/new?template=feature_request.md).
66 |
67 | If you're only fixing a bug, it's fine to submit a pull request right away but we still recommend that you file an issue detailing what you're fixing. This is helpful in case we don't accept that specific fix but want to keep track of the issue.
68 |
69 | ### Sending a pull request
70 |
71 | Small pull requests are much easier to review and more likely to get merged. Make sure the PR does only one thing, otherwise please split it.
72 |
73 | Please make sure the following is done when submitting a pull request:
74 |
75 | 1. Fork [the repository](https://github.com/rixo/svelte-hmr) and create your branch from `main`.
76 | 1. Describe your **test plan** in your pull request description. Make sure to test your changes.
77 | 1. Make sure your code lints (`pnpm run lint`).
78 | 1. Make sure your tests pass (`pnpm run test`).
79 |
80 | All pull requests should be opened against the `main` branch.
81 |
82 | #### Tests
83 |
84 | Integration tests for new features or regression tests as part of a bug fix are very welcome.
85 | Add them in `test`.
86 |
87 | #### Documentation
88 |
89 | If you've changed APIs, update the documentation.
90 |
91 | #### Changelogs
92 |
93 | For changes to be reflected in package changelogs, run `pnpm changeset` and follow the prompts.
94 | You should always select the packages you've changed, Most likely `svelte-hmr`.
95 |
96 | ### What happens next?
97 |
98 | The core Svelte team will be monitoring for pull requests. Do help us by making your pull request easy to review by following the guidelines above.
99 |
100 | ## Style guide
101 |
102 | [Eslint](https://eslint.org) will catch most styling issues that may exist in your code. You can check the status of your code styling by simply running `pnpm run lint`.
103 |
104 | ## License
105 |
106 | By contributing to svelte-hmr, you agree that your contributions will be licensed under its [ISC license](./LICENSE).
107 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright 2019 - 2020, rixo and the svelte-hmr contributors.
2 |
3 | Permission to use, copy, modify, and/or distribute this software for any
4 | purpose with or without fee is hereby granted, provided that the above
5 | copyright notice and this permission notice appear in all copies.
6 |
7 | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 | WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 | MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
10 | ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 | OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 | CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # svelte-hmr
2 |
3 | HMR engine for Svelte.
4 |
5 | See [svelte-hmr](/packages/svelte-hmr#readme) package for all details.
6 |
--------------------------------------------------------------------------------
/jsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "@tsconfig/svelte/tsconfig.json",
3 | "include": ["packages/**/*", "playground/**/*"],
4 | "exclude": ["node_modules", "**/*.bak"],
5 | "compilerOptions": {
6 | "checkJs": true,
7 | "moduleResolution": "node16",
8 | "module": "es2022",
9 | "resolveJsonModule": true,
10 | "skipLibCheck": true,
11 | //"noUnusedLocals": true,
12 | //"types": []
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/mount-tmp-playground.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Mount a tmpfs on playground-tmp directory.
4 | #
5 | # This is entirely optional. The point is to save write cycles on your disk.
6 | #
7 | # Usage:
8 | #
9 | # export TMP_PLAYGROUND_DIR=playground-tmp
10 | # ./mount-tmp-playground.sh
11 | # cd playground
12 | # pnpm test
13 | #
14 |
15 | TMP_PLAYGROUND_DIR=${TMP_PLAYGROUND_DIR:-"playground-tmp"}
16 |
17 | if [ "$1" == "-u" ] || [ "$1" == "--unmount" ]; then
18 | umount "$TMP_PLAYGROUND_DIR"
19 | else
20 | mkdir -p "$TMP_PLAYGROUND_DIR"
21 | mount -o size=16G -t tmpfs none playground-tmp
22 | fi
23 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "svelte-hmr-monorepo",
3 | "private": true,
4 | "description": "Bundler agnostic HMR utils for Svelte 3",
5 | "license": "ISC",
6 | "homepage": "https://github.com/sveltejs/svelte-hmr",
7 | "bugs": {
8 | "url": "https://github.com/sveltejs/svelte-hmr/issues"
9 | },
10 | "repository": {
11 | "type": "git",
12 | "url": "https://github.com/sveltejs/svelte-hmr"
13 | },
14 | "packageManager": "pnpm@8.14.0",
15 | "engines": {
16 | "pnpm": ">=7.0.0"
17 | },
18 | "pnpm": {
19 | "overrides": {
20 | "svelte-hmr": "workspace:*",
21 | "svelte": "$svelte"
22 | }
23 | },
24 | "devDependencies": {
25 | "@changesets/cli": "^2.27.8",
26 | "@svitejs/changesets-changelog-github-compact": "^0.1.1",
27 | "@tsconfig/svelte": "^4.0.1",
28 | "eslint": "^8.44.0",
29 | "prettier": "^2.8.8",
30 | "prettier-plugin-jsdoc": "^0.4.2",
31 | "svelte": "^4.0.0",
32 | "svelte-check": "^3.4.4",
33 | "typescript": "^5.0.4"
34 | },
35 | "scripts": {
36 | "release": "pnpm changeset publish",
37 | "lint": "pnpm --recursive lint",
38 | "test": "pnpm --recursive test"
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/packages/svelte-hmr/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # svelte-hmr
2 |
3 | ## 0.16.0
4 |
5 | ### Minor Changes
6 |
7 | - Update native adapter for support of NativeScript 8 ([`b8aabc0`](https://github.com/sveltejs/svelte-hmr/commit/b8aabc09d87821a10095224d4ab11fb83d7b243c))
8 |
9 | ## 0.15.3
10 |
11 | ### Patch Changes
12 |
13 | - Fix injecting imports whose paths contain special characters ([#78](https://github.com/sveltejs/svelte-hmr/pull/78))
14 |
15 | ## 0.15.2
16 |
17 | ### Patch Changes
18 |
19 | - Accept Svelte 4 as peer dependency ([`3b4300c`](https://github.com/sveltejs/svelte-hmr/commit/3b4300cc8acc734c34dbfafc495c06d5d4d17803))
20 |
21 | ## 0.15.1
22 |
23 | ### Patch Changes
24 |
25 | - support 'external' as value for compileOptions.css ([#63](https://github.com/sveltejs/svelte-hmr/pull/63))
26 |
27 | ## 0.15.0
28 |
29 | ### Minor Changes
30 |
31 | - Add partialAccept option to fix HMR support of `
58 | ```
59 |
60 | #### preserveAllLocalStateKey
61 |
62 | Type: `string`
63 | Default: `'@hmr:keep-all'`
64 |
65 | Force preservation of all local variables of this component.
66 |
67 | ```svelte
68 |
69 |
70 |
75 | ```
76 |
77 | #### preserveLocalStateKey
78 |
79 | Type: `string`
80 | Default: `'@hmr:keep'`
81 |
82 | Force preservation of a given local variable in this component.
83 |
84 | ```svelte
85 |
93 | ```
94 |
95 | #### optimistic
96 |
97 | Type: `bool`
98 | Default: `false`
99 |
100 | When `false`, runtime errors during component init (i.e. when your `
166 |
167 |
{x}
168 | ``` 169 | 170 | If you replace `let x = 1` by `let x = 10` and save, the previous value of `x` will be preserved. That is, `x` will be 2 and not 10. The restoration of previous state happens _after_ the init code of the component has run, so the value will not be 11 either, despite the `x++` that is still here. 171 | 172 | If you want this behaviour for all the state of all your components, you can enable it by setting the `preserveLocalState` option to `true`. 173 | 174 | If you then want to disable it for just one particular file, or just temporarily, you can turn it off by adding a `// @hmr:reset` comment somewhere in your component. 175 | 176 | On the contrary, if you keep the default `preserveLocalState` to `false`, you can enable preservation of all the local state of a given component by adding the following comment: `// @hmr:keep-all`. You can also preserve only the state of some specific variables, by annotating them with: `// @hmr:keep`. 177 | 178 | For example: 179 | 180 | ```svelte 181 | 190 | ``` 191 | 192 | ## Svelte HMR tools 193 | 194 | ### Vite 195 | 196 | The [official Svelte plugin for Vite][vite-plugin-svelte] has HMR support. 197 | 198 | ### Webpack 199 | 200 | The [official loader for Webpack][svelte-loader] now has HMR support. 201 | 202 | ### Rollup 203 | 204 | Rollup does not natively support HMR, so we recommend using Vite. However, if you'd like to add HMR support to Rollup, the best way to get started is to refer to [svelte-template-hot], which demonstrates usage of both [rollup-plugin-hot] and [rollup-plugin-svelte-hot]. 205 | 206 | ### Svelte Native 207 | 208 | The official [Svelte Native template][svelte-native-template] already includes HMR support. 209 | 210 | ## License 211 | 212 | [ISC](LICENSE) 213 | 214 | [vite-plugin-svelte]: https://www.npmjs.com/package/@sveltejs/vite-plugin-svelte 215 | [svelte-loader]: https://github.com/sveltejs/svelte-loader 216 | [rollup-plugin-hot]: https://github.com/rixo/rollup-plugin-hot 217 | [rollup-plugin-svelte-hot]: https://github.com/rixo/rollup-plugin-svelte-hot 218 | [rollup-plugin-svelte]: https://github.com/rollup/rollup-plugin-svelte 219 | [svelte-template-hot]: https://github.com/rixo/svelte-template-hot 220 | [svelte-template]: https://github.com/sveltejs/template 221 | [svelte-native-template]: https://github.com/halfnelson/svelte-native-template 222 | [svelte-loader-hot]: https://github.com/rixo/svelte-loader-hot 223 | [svelte-template-webpack-hot]: https://github.com/rixo/svelte-template-webpack-hot 224 | -------------------------------------------------------------------------------- /packages/svelte-hmr/index.js: -------------------------------------------------------------------------------- 1 | const createMakeHotFactory = require('./lib/make-hot.js') 2 | const { resolve } = require('path') 3 | const { name, version } = require('./package.json') 4 | 5 | const resolveAbsoluteImport = target => resolve(__dirname, target) 6 | 7 | const createMakeHot = createMakeHotFactory({ 8 | pkg: { name, version }, 9 | resolveAbsoluteImport, 10 | }) 11 | 12 | module.exports = { createMakeHot } 13 | -------------------------------------------------------------------------------- /packages/svelte-hmr/lib/css-only.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Injects a `{}*` CSS rule to force Svelte compiler to scope every elements. 3 | */ 4 | export const injectScopeEverythingCssRule = (parse, code) => { 5 | const { css } = parse(code) 6 | if (!css) return code 7 | const { 8 | content: { end }, 9 | } = css 10 | return code.slice(0, end) + '*{}' + code.slice(end) 11 | } 12 | 13 | export const normalizeJsCode = code => { 14 | // Svelte now adds locations in dev mode, code locations can change when 15 | // CSS change, but we're unaffected (not real behaviour changes) 16 | code = code.replace(/\badd_location\s*\([^)]*\)\s*;?/g, '') 17 | return code 18 | } 19 | -------------------------------------------------------------------------------- /packages/svelte-hmr/lib/make-hot.js: -------------------------------------------------------------------------------- 1 | const globalName = '___SVELTE_HMR_HOT_API' 2 | const globalAdapterName = '___SVELTE_HMR_HOT_API_PROXY_ADAPTER' 3 | 4 | const defaultHotOptions = { 5 | // preserve all local state 6 | preserveLocalState: false, 7 | 8 | // escape hatchs from preservation of local state 9 | // 10 | // disable preservation of state for this component 11 | noPreserveStateKey: ['@hmr:reset', '@!hmr'], 12 | // enable preservation of state for all variables in this component 13 | preserveAllLocalStateKey: '@hmr:keep-all', 14 | // enable preservation of state for a given variable (must be inline or 15 | // above the target variable or variables; can be repeated) 16 | preserveLocalStateKey: '@hmr:keep', 17 | 18 | // don't reload on fatal error 19 | noReload: false, 20 | // try to recover after runtime errors during component init 21 | // defaults to false because some runtime errors are fatal and require a full reload 22 | optimistic: false, 23 | // auto accept modules of components that have named exports (i.e. exports 24 | // from context="module") 25 | acceptNamedExports: true, 26 | // auto accept modules of components have accessors (either accessors compile 27 | // option, or
12 | {"const product = 1 * 1; export default product;"}
13 |
14 | `,
15 | },
16 | expect: `
17 |
18 | const product = 1 * 1; export default product;
19 |
20 | `,
21 | },
22 | ])
23 | )
24 | })
25 |
--------------------------------------------------------------------------------
/playground/basic/vite.config.js:
--------------------------------------------------------------------------------
1 | import { svelte } from '@sveltejs/vite-plugin-svelte'
2 | import { defineConfig } from 'vite'
3 |
4 | export default defineConfig({
5 | plugins: [svelte()],
6 | })
7 |
--------------------------------------------------------------------------------
/playground/jsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../jsconfig.json",
3 | "include": ["**/*"],
4 | "compilerOptions": {
5 | "paths": {
6 | "$test": ["./$test/index.js"]
7 | }
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/playground/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@svelte-hmr/playground",
3 | "private": true,
4 | "type": "module",
5 | "version": "0.0.0",
6 | "devDependencies": {
7 | "fs-extra": "^11.1.1",
8 | "playwright-chromium": "^1.34.3",
9 | "sanitize-html": "^2.11.0",
10 | "vite": "^5.1.1",
11 | "vitest": "^1.2.2"
12 | },
13 | "scripts": {
14 | "test": "vitest"
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/playground/vitest.config.js:
--------------------------------------------------------------------------------
1 | import { resolve } from 'node:path'
2 | import { defineConfig } from 'vitest/config'
3 |
4 | import { isKeep } from './$test/config.js'
5 |
6 | const timeout = process.env.CI ? 50000 : isKeep ? 0 : 30000
7 |
8 | export default defineConfig({
9 | resolve: {
10 | alias: {
11 | $test: resolve(__dirname, './$test/index.js'),
12 | },
13 | },
14 | test: {
15 | testTimeout: timeout,
16 | hookTimeout: timeout,
17 | globalSetup: ['./vitestGlobalSetup.js'],
18 | setupFiles: ['./vitestSetup.js'],
19 | sequence: {
20 | concurrent: true,
21 | },
22 | },
23 | })
24 |
--------------------------------------------------------------------------------
/playground/vitestGlobalSetup.js:
--------------------------------------------------------------------------------
1 | import { chromium } from 'playwright-chromium'
2 | import fs from 'fs-extra'
3 | import path from 'node:path'
4 |
5 | import {
6 | ROOT_DIR,
7 | GLOBAL_DIR,
8 | WS_ENDPOINT_FILE,
9 | GLOBAL_STATE_FILE,
10 | PLAYGROUND_DIR,
11 | isOpen,
12 | isCI,
13 | } from './$test/config.js'
14 | import { call, randomId } from './$test/util.js'
15 |
16 | const TMP_PLAYGROUND_DIR = process.env.TMP_PLAYGROUND_DIR
17 | ? path.resolve(ROOT_DIR, process.env.TMP_PLAYGROUND_DIR)
18 | : path.join(ROOT_DIR, `playground-${randomId()}`)
19 |
20 | const initBrowserServer = async () => {
21 | const browserServer = await chromium.launchServer({
22 | headless: !isOpen,
23 | devtools: isOpen,
24 | args: isCI ? ['--no-sandbox', '--disable-setuid-sandbox'] : undefined,
25 | })
26 |
27 | await fs.writeFile(WS_ENDPOINT_FILE, browserServer.wsEndpoint())
28 |
29 | return async () => {
30 | await browserServer?.close()
31 | }
32 | }
33 |
34 | const initGlobalState = async () => {
35 | const data = JSON.stringify({
36 | tmpPlaygroundDir: TMP_PLAYGROUND_DIR,
37 | })
38 | await fs.writeFile(GLOBAL_STATE_FILE, data, 'utf8')
39 | return async () => {
40 | await fs.remove(GLOBAL_STATE_FILE)
41 | }
42 | }
43 |
44 | const initFixtures = async () => {
45 | await fs.mkdirp(TMP_PLAYGROUND_DIR)
46 |
47 | const nodeModulesDir = path.resolve(PLAYGROUND_DIR, 'node_modules')
48 |
49 | await fs.copy(PLAYGROUND_DIR, TMP_PLAYGROUND_DIR, {
50 | // keep all files + node_modules directory
51 | /** @param {string} item */
52 | filter: (item) =>
53 | item === PLAYGROUND_DIR ||
54 | item.includes('.') ||
55 | item === nodeModulesDir ||
56 | item.startsWith(nodeModulesDir + '/'),
57 | })
58 |
59 | return async () => {
60 | if (process.env.TMP_PLAYGROUND_DIR) {
61 | await fs.emptyDir(TMP_PLAYGROUND_DIR)
62 | } else {
63 | await fs.remove(TMP_PLAYGROUND_DIR)
64 | }
65 | }
66 | }
67 |
68 | const inits = [initGlobalState, initBrowserServer, initFixtures]
69 |
70 | /** @type {(() => Promise