├── .editorconfig
├── .eslintignore
├── .eslintrc.js
├── .gitattributes
├── .github
├── CODEOWNERS
├── CONTRIBUTING.md
├── FUNDING.yml
├── ISSUE_TEMPLATE.md
├── ISSUE_TEMPLATE
│ ├── BUG.md
│ ├── DOCS.md
│ ├── FEATURE.md
│ ├── MODIFICATION.md
│ └── SUPPORT.md
├── PULL_REQUEST_TEMPLATE.md
└── workflows
│ └── nodejs.yml
├── .gitignore
├── .prettierignore
├── CHANGELOG.md
├── LICENSE
├── README.md
├── babel.config.js
├── commitlint.config.js
├── globalSetupTest.js
├── husky.config.js
├── jest.config.js
├── lint-staged.config.js
├── package-lock.json
├── package.json
├── setupTest.js
├── src
├── cjs.js
├── index.js
├── options.json
├── runtime
│ └── inline.js
├── supportWebpack4.js
├── supportWebpack5.js
└── utils.js
└── test
├── __snapshots__
├── chunkFilename-option.test.js.snap
├── esModule-option.test.js.snap
├── filename-options.test.js.snap
├── inline-option.test.js.snap
├── loader.test.js.snap
├── publicPath.test.js.snap
├── sourceMapperRegexp.test.js.snap
├── validate-options.test.js.snap
└── worker-option.test.js.snap
├── chunkFilename-option.test.js
├── cjs.test.js
├── esModule-option.test.js
├── filename-options.test.js
├── fixtures
├── basic
│ ├── entry.js
│ ├── index.html
│ └── worker.js
├── chunks
│ ├── chunk.js
│ ├── entry.js
│ ├── index.html
│ └── worker.js
├── external
│ ├── entry.js
│ ├── index.html
│ └── worker.js
├── name
│ ├── TypeDetection.js
│ ├── entry.js
│ └── index.html
├── nodejs-core-modules
│ ├── entry.js
│ └── worker.js
├── query
│ ├── entry.js
│ ├── index.html
│ └── my-worker-name.js
└── wasm
│ ├── add.wasm
│ ├── entry.js
│ ├── index.html
│ └── worker.js
├── helpers
├── compile.js
├── execute.js
├── getCompiler.js
├── getErrors.js
├── getModuleSource.js
├── getResultFromBrowser.js
├── getWarnings.js
├── index.js
├── normalizeErrors.js
├── readAsset.js
└── readAssets.js
├── inline-option.test.js
├── loader.test.js
├── publicPath.test.js
├── sourceMapperRegexp.test.js
├── validate-options.test.js
└── worker-option.test.js
/.editorconfig:
--------------------------------------------------------------------------------
1 | # editorconfig.org
2 |
3 | [*]
4 | charset = utf-8
5 | indent_style = space
6 | indent_size = 2
7 | end_of_line = lf
8 | insert_final_newline = true
9 | trim_trailing_whitespace = true
10 |
11 | [*.md]
12 | trim_trailing_whitespace = false
13 |
--------------------------------------------------------------------------------
/.eslintignore:
--------------------------------------------------------------------------------
1 | /coverage
2 | /dist
3 | /node_modules
4 | /test/fixtures
5 | /test/outputs
6 |
--------------------------------------------------------------------------------
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | root: true,
3 | extends: ["@webpack-contrib/eslint-config-webpack", "prettier"],
4 | };
5 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | package-lock.json -diff
2 | * text=auto
3 | bin/* eol=lf
4 | yarn.lock -diff
--------------------------------------------------------------------------------
/.github/CODEOWNERS:
--------------------------------------------------------------------------------
1 | # These are the default owners for everything in
2 | # webpack-contrib
3 | @webpack-contrib/org-maintainers
4 |
5 | # Add repository specific users / groups
6 | # below here for libs that are not maintained by the org.
--------------------------------------------------------------------------------
/.github/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing in @webpack-contrib
2 |
3 | We'd always love contributions to further improve the webpack / webpack-contrib ecosystem!
4 | Here are the guidelines we'd like you to follow:
5 |
6 | - [Questions and Problems](#question)
7 | - [Issues and Bugs](#issue)
8 | - [Feature Requests](#feature)
9 | - [Pull Request Submission Guidelines](#submit-pr)
10 | - [Commit Message Conventions](#commit)
11 |
12 | ## Got a Question or Problem?
13 |
14 | Please submit support requests and questions to StackOverflow using the tag [[webpack]](http://stackoverflow.com/tags/webpack).
15 | StackOverflow is better suited for this kind of support though you may also inquire in [Webpack Gitter](https://gitter.im/webpack/webpack).
16 | The issue tracker is for bug reports and feature discussions.
17 |
18 | ## Found an Issue or Bug?
19 |
20 | Before you submit an issue, please search the issue tracker, maybe an issue for your problem already exists and the discussion might inform you of workarounds readily available.
21 |
22 | We want to fix all the issues as soon as possible, but before fixing a bug we need to reproduce and confirm it. In order to reproduce bugs, we ask that you to provide a minimal reproduction scenario (github repo or failing test case). Having a live, reproducible scenario gives us a wealth of important information without going back & forth to you with additional questions like:
23 |
24 | - version of Webpack used
25 | - version of the loader / plugin you are creating a bug report for
26 | - the use-case that fails
27 |
28 | A minimal reproduce scenario allows us to quickly confirm a bug (or point out config problems) as well as confirm that we are fixing the right problem.
29 |
30 | We will be insisting on a minimal reproduce scenario in order to save maintainers time and ultimately be able to fix more bugs. We understand that sometimes it might be hard to extract essentials bits of code from a larger code-base but we really need to isolate the problem before we can fix it.
31 |
32 | Unfortunately, we are not able to investigate / fix bugs without a minimal reproduction, so if we don't hear back from you we are going to close an issue that doesn't have enough info to be reproduced.
33 |
34 | ## Feature Requests?
35 |
36 | You can _request_ a new feature by creating an issue on Github.
37 |
38 | If you would like to _implement_ a new feature, please submit an issue with a proposal for your work `first`, to be sure that particular makes sense for the project.
39 |
40 | ## Pull Request Submission Guidelines
41 |
42 | Before you submit your Pull Request (PR) consider the following guidelines:
43 |
44 | - Search Github for an open or closed PR that relates to your submission. You don't want to duplicate effort.
45 | - Commit your changes using a descriptive commit message that follows our [commit message conventions](#commit). Adherence to these conventions is necessary because release notes are automatically generated from these messages.
46 | - Fill out our `Pull Request Template`. Your pull request will not be considered if it is ignored.
47 | - Please sign the `Contributor License Agreement (CLA)` when a pull request is opened. We cannot accept your pull request without this. Make sure you sign with the primary email address associated with your local / github account.
48 |
49 | ## Webpack Contrib Commit Conventions
50 |
51 | Each commit message consists of a **header**, a **body** and a **footer**. The header has a special
52 | format that includes a **type**, a **scope** and a **subject**:
53 |
54 | ```
55 | ():
56 |
57 |
58 |
59 |
60 | ```
61 |
62 | The **header** is mandatory and the **scope** of the header is optional.
63 |
64 | Any line of the commit message cannot be longer 100 characters! This allows the message to be easier
65 | to read on GitHub as well as in various git tools.
66 |
67 | The footer should contain a [closing reference to an issue](https://help.github.com/articles/closing-issues-via-commit-messages/) if any.
68 |
69 | Examples:
70 |
71 | ```
72 | docs(readme): update install instructions
73 | ```
74 |
75 | ```
76 | fix: refer to the `entrypoint` instead of the first `module`
77 | ```
78 |
79 | ### Revert
80 |
81 | If the commit reverts a previous commit, it should begin with `revert:`, followed by the header of the reverted commit.
82 | In the body it should say: `This reverts commit .`, where the hash is the SHA of the commit being reverted.
83 |
84 | ### Type
85 |
86 | Must be one of the following:
87 |
88 | - **build**: Changes that affect the build system or external dependencies (example scopes: babel, npm)
89 | - **chore**: Changes that fall outside of build / docs that do not effect source code (example scopes: package, defaults)
90 | - **ci**: Changes to our CI configuration files and scripts (example scopes: circleci, travis)
91 | - **docs**: Documentation only changes (example scopes: readme, changelog)
92 | - **feat**: A new feature
93 | - **fix**: A bug fix
94 | - **perf**: A code change that improves performance
95 | - **refactor**: A code change that neither fixes a bug nor adds a feature
96 | - **revert**: Used when reverting a committed change
97 | - **style**: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons)
98 | - **test**: Addition of or updates to Jest tests
99 |
100 | ### Scope
101 |
102 | The scope is subjective & depends on the `type` see above. A good example would be a change to a particular class / module.
103 |
104 | ### Subject
105 |
106 | The subject contains a succinct description of the change:
107 |
108 | - use the imperative, present tense: "change" not "changed" nor "changes"
109 | - don't capitalize the first letter
110 | - no dot (.) at the end
111 |
112 | ### Body
113 |
114 | Just as in the **subject**, use the imperative, present tense: "change" not "changed" nor "changes".
115 | The body should include the motivation for the change and contrast this with previous behavior.
116 |
117 | ### Footer
118 |
119 | The footer should contain any information about **Breaking Changes** and is also the place to
120 | reference GitHub issues that this commit **Closes**.
121 |
122 | **Breaking Changes** should start with the word `BREAKING CHANGE:` with a space or two newlines. The rest of the commit message is then used for this.
123 |
124 | Example
125 |
126 | ```
127 | BREAKING CHANGE: Updates to `Chunk.mapModules`.
128 |
129 | This release is not backwards compatible with `Webpack 2.x` due to breaking changes in webpack/webpack#4764
130 | Migration: see webpack/webpack#5225
131 |
132 | ```
133 |
134 | ## Testing Your Pull Request
135 |
136 | You may have the need to test your changes in a real-world project or dependent
137 | module. Thankfully, Github provides a means to do this. Add a dependency to the
138 | `package.json` for such a project as follows:
139 |
140 | ```json
141 | {
142 | "devDependencies": {
143 | "worker-loader": "webpack-contrib/worker-loader#{id}/head"
144 | }
145 | }
146 | ```
147 |
148 | Where `{id}` is the # ID of your Pull Request.
149 |
150 | ## Contributor License Agreement
151 |
152 | When submitting your contribution, a CLA (Contributor License Agreement) bot will come by to verify that you signed the [CLA](https://cla.js.foundation/webpack-contrib/worker-loader).
153 | If it is your first time, it will link you to the right place to sign it.
154 | However, if you have committed your contributions using an email that is not the same as your email used on GitHub, the CLA bot can't accept your contribution.
155 |
156 | Run `git config user.email` to see your Git email, and verify it with [your GitHub email](https://github.com/settings/emails).
157 |
158 | ## Thanks
159 |
160 | For your interest, time, understanding, and for following this simple guide.
161 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | open_collective: webpack
2 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
17 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/BUG.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: 🐛 Bug Report
3 | about: Something went awry and you'd like to tell us about it.
4 | ---
5 |
6 |
7 |
8 |
9 | ### Bug report
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 | ### Actual Behavior
18 |
19 |
20 |
21 | ### Expected Behavior
22 |
23 |
24 |
25 |
26 | ### How Do We Reproduce?
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 | ### Please paste the results of `npx webpack-cli info` here, and mention other relevant information
36 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/DOCS.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: 📚 Documentation
3 | about: Are the docs lacking or missing something? Do they need some new 🔥 hotness? Tell us here.
4 | ---
5 |
6 |
7 |
8 |
9 | Documentation Is:
10 |
11 |
12 |
13 | - [ ] Missing
14 | - [ ] Needed
15 | - [ ] Confusing
16 | - [ ] Not Sure?
17 |
18 | ### Please Explain in Detail...
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 | ### Your Proposal for Changes
27 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/FEATURE.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: ✨ Feature Request
3 | about: Suggest an idea for this project
4 | ---
5 |
6 |
7 |
8 |
9 | ### Feature Proposal
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 | ### Feature Use Case
18 |
19 | ### Please paste the results of `npx webpack-cli info` here, and mention other relevant information
20 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/MODIFICATION.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: 🔧 Modification Request
3 | about: Would you like something work differently? Have an alternative approach? This is the template for you.
4 | ---
5 |
6 |
7 |
8 |
9 | ### Modification Proposal
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 | ### Expected Behavior / Situation
18 |
19 | ### Actual Behavior / Situation
20 |
21 | ### Please paste the results of `npx webpack-cli info` here, and mention other relevant information
22 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/SUPPORT.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: 🆘 Support, Help, and Advice
3 | about: 👉🏽 Need support, help, or advice? Don't open an issue! Head to https://github.com/webpack/webpack/discussions, StackOverflow or https://gitter.im/webpack/webpack.
4 | ---
5 |
6 | Hey there! If you need support, help, or advice then this is not the place to ask.
7 | Please visit [Discussions](https://github.com/webpack/webpack/discussions), [StackOverflow](https://stackoverflow.com/questions/tagged/webpack)
8 | or [the Webpack Gitter](https://gitter.im/webpack/webpack) instead.
9 |
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
10 |
11 | This PR contains a:
12 |
13 | - [ ] **bugfix**
14 | - [ ] new **feature**
15 | - [ ] **code refactor**
16 | - [ ] **test update**
17 | - [ ] **typo fix**
18 | - [ ] **metadata update**
19 |
20 | ### Motivation / Use-Case
21 |
22 |
27 |
28 | ### Breaking Changes
29 |
30 |
34 |
35 | ### Additional Info
36 |
--------------------------------------------------------------------------------
/.github/workflows/nodejs.yml:
--------------------------------------------------------------------------------
1 | name: worker-loader
2 |
3 | on:
4 | push:
5 | branches:
6 | - master
7 | - next
8 | pull_request:
9 | branches:
10 | - master
11 | - next
12 |
13 | jobs:
14 | lint:
15 | name: Lint - ${{ matrix.os }} - Node v${{ matrix.node-version }}
16 |
17 | env:
18 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
19 |
20 | strategy:
21 | matrix:
22 | os: [ubuntu-latest]
23 | node-version: [12.x]
24 |
25 | runs-on: ${{ matrix.os }}
26 |
27 | steps:
28 | - uses: actions/checkout@v2
29 | with:
30 | fetch-depth: 0
31 |
32 | - name: Use Node.js ${{ matrix.node-version }}
33 | uses: actions/setup-node@v2
34 | with:
35 | node-version: ${{ matrix.node-version }}
36 | cache: "npm"
37 |
38 | - name: Use latest NPM
39 | run: sudo npm i -g npm
40 |
41 | - name: Install dependencies
42 | run: npm ci
43 |
44 | - name: Lint
45 | run: npm run lint
46 |
47 | # - name: Security audit
48 | # run: npm run security
49 |
50 | - name: Check commit message
51 | uses: wagoid/commitlint-github-action@v4
52 |
53 | test:
54 | name: Test - ${{ matrix.os }} - Node v${{ matrix.node-version }}, Webpack ${{ matrix.webpack-version }}
55 |
56 | strategy:
57 | matrix:
58 | os: [ubuntu-latest, windows-latest, macos-latest]
59 | node-version: [10.x, 12.x, 14.x]
60 | webpack-version: [4, latest]
61 |
62 | runs-on: ${{ matrix.os }}
63 |
64 | steps:
65 | - name: Setup Git
66 | if: matrix.os == 'windows-latest'
67 | run: git config --global core.autocrlf input
68 |
69 | - uses: actions/checkout@v2
70 |
71 | - name: Use Node.js ${{ matrix.node-version }}
72 | uses: actions/setup-node@v2
73 | with:
74 | node-version: ${{ matrix.node-version }}
75 | cache: "npm"
76 |
77 | - name: Use latest NPM on ubuntu/macos
78 | if: matrix.os == 'ubuntu-latest' || matrix.os == 'macos-latest'
79 | run: sudo npm i -g npm
80 |
81 | - name: Use latest NPM on windows
82 | if: matrix.os == 'windows-latest'
83 | run: npm i -g npm
84 |
85 | - name: Install dependencies
86 | run: npm ci
87 |
88 | - name: Install webpack ${{ matrix.webpack-version }}
89 | run: npm i webpack@${{ matrix.webpack-version }}
90 |
91 | - name: Run tests for webpack version ${{ matrix.webpack-version }}
92 | run: npm run test:coverage -- --ci
93 |
94 | - name: Submit coverage data to codecov
95 | uses: codecov/codecov-action@v2
96 | with:
97 | token: ${{ secrets.CODECOV_TOKEN }}
98 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | logs
2 | *.log
3 | npm-debug.log*
4 | .eslintcache
5 | /coverage
6 | /dist
7 | /local
8 | /reports
9 | /node_modules
10 | /test/outputs
11 | .DS_Store
12 | Thumbs.db
13 | .idea
14 | .vscode
15 | *.sublime-project
16 | *.sublime-workspace
17 | *.iml
18 |
--------------------------------------------------------------------------------
/.prettierignore:
--------------------------------------------------------------------------------
1 | /coverage
2 | /dist
3 | /node_modules
4 | /test/fixtures
5 | /test/outputs
6 | CHANGELOG.md
7 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4 |
5 | ### [3.0.8](https://github.com/webpack-contrib/worker-loader/compare/v3.0.7...v3.0.8) (2021-02-11)
6 |
7 |
8 | ### Bug Fixes
9 |
10 | * make inline workers work from inside workers ([#307](https://github.com/webpack-contrib/worker-loader/issues/307)) ([2abd129](https://github.com/webpack-contrib/worker-loader/commit/2abd129a322d631caf619622cd65825699bb183a))
11 |
12 | ### [3.0.7](https://github.com/webpack-contrib/worker-loader/compare/v3.0.6...v3.0.7) (2020-12-23)
13 |
14 |
15 | ### Bug Fixes
16 |
17 | * serializing big strings ([#304](https://github.com/webpack-contrib/worker-loader/issues/304)) ([a0de29b](https://github.com/webpack-contrib/worker-loader/commit/a0de29b497876eb462271ca5ebbeb3ffe1c1d1c4))
18 |
19 | ### [3.0.6](https://github.com/webpack-contrib/worker-loader/compare/v3.0.5...v3.0.6) (2020-12-02)
20 |
21 |
22 | ### Bug Fixes
23 |
24 | * set a name to exported function ([#299](https://github.com/webpack-contrib/worker-loader/issues/299)) ([15cf407](https://github.com/webpack-contrib/worker-loader/commit/15cf407ad6baeb09e2cbb5d7b4b869cc63bfac7f))
25 |
26 | ### [3.0.5](https://github.com/webpack-contrib/worker-loader/compare/v3.0.4...v3.0.5) (2020-10-16)
27 |
28 |
29 | ### Bug Fixes
30 |
31 | * determine webpack peer dependency version ([#296](https://github.com/webpack-contrib/worker-loader/issues/296)) ([8c63449](https://github.com/webpack-contrib/worker-loader/commit/8c634495419b4becc32b83e24c21e36ff720a2cd))
32 |
33 | ### [3.0.4](https://github.com/webpack-contrib/worker-loader/compare/v3.0.3...v3.0.4) (2020-10-09)
34 |
35 | ### Chore
36 |
37 | * update `schema-utils`
38 |
39 | ### [3.0.3](https://github.com/webpack-contrib/worker-loader/compare/v3.0.2...v3.0.3) (2020-09-22)
40 |
41 |
42 | ### Bug Fixes
43 |
44 | * remove unnecessary webpack sourceURL ([#289](https://github.com/webpack-contrib/worker-loader/issues/289)) ([eef2757](https://github.com/webpack-contrib/worker-loader/commit/eef27574160f519c344dfa5fd981b7ac561a8939))
45 | * compatibility with eval source maps ([#286](https://github.com/webpack-contrib/worker-loader/issues/286)) ([0d4624c](https://github.com/webpack-contrib/worker-loader/commit/0d4624c178c426aa97e5175a5f321e43de482c2b))
46 |
47 | ### [3.0.2](https://github.com/webpack-contrib/worker-loader/compare/v3.0.1...v3.0.2) (2020-08-22)
48 |
49 |
50 | ### Bug Fixes
51 |
52 | * SSR compatibility ([#284](https://github.com/webpack-contrib/worker-loader/issues/284)) ([ca4a963](https://github.com/webpack-contrib/worker-loader/commit/ca4a963e93fe5efcdf84cda0dbe571d293f079a5))
53 |
54 | ### [3.0.1](https://github.com/webpack-contrib/worker-loader/compare/v3.0.0...v3.0.1) (2020-08-05)
55 |
56 |
57 | ### Bug Fixes
58 |
59 | * compatibility with webpack@5 cache ([#279](https://github.com/webpack-contrib/worker-loader/issues/279)) ([ee519b1](https://github.com/webpack-contrib/worker-loader/commit/ee519b1d283dbb599385fe2932c99c929b09db36))
60 | * interpolation `[name]` for the `filename` option ([#277](https://github.com/webpack-contrib/worker-loader/issues/277)) ([5efa77a](https://github.com/webpack-contrib/worker-loader/commit/5efa77a64d8fbce123b289461234ac3a8812fb54))
61 |
62 | ## [3.0.0](https://github.com/webpack-contrib/worker-loader/compare/v2.0.0...v3.0.0) (2020-08-01)
63 |
64 |
65 | ### ⚠ BREAKING CHANGES
66 |
67 | * minimum supported Node.js version is `10.13`
68 | * minimum supported webpack version is `4`
69 | * the `name` option was renamed to the `filename` option
70 | * switch on ES module syntax by default, use the `esModule` option if you need backward compatibility with Common JS modules
71 | * the `fallback` option was removed in favor the `inline` option, the `inline` option accepts only `fallback` and `no-fallback` values
72 | * the `publicPath` option default value based on `output.publicPath`
73 | * the `filename` option default value based on `output.filename`
74 |
75 |
76 | ### Features
77 |
78 | * added the `worker` option (replaces [#178](https://github.com/webpack-contrib/worker-loader/issues/178)) ([#247](https://github.com/webpack-contrib/worker-loader/issues/247)) ([f03498d](https://github.com/webpack-contrib/worker-loader/commit/f03498d22c6a3737b724c51bdfb56627e33b57b2))
79 | * added the `chunkFilename` option, default value based on `output.chunkFilename` ([905ed7b](https://github.com/webpack-contrib/worker-loader/commit/905ed7b028bbcb646050a1d09096dbe2fc1feb42))
80 | * added the `esModule` option
81 | * allow to use any web worker constructor and options for constructor
82 | * the `publicPath` option can be `Function`
83 | * the `filename` (previously `name`) option can be `Function`
84 |
85 |
86 | ### Bug Fixes
87 |
88 | * support `WASM` ([152634c](https://github.com/webpack-contrib/worker-loader/commit/152634c0d8866d248ced3b6e5ac02761c978ae1a))
89 | * respect `externals` ([#264](https://github.com/webpack-contrib/worker-loader/issues/264)) ([1e761ed](https://github.com/webpack-contrib/worker-loader/commit/1e761edcbfc8b214ae3a19f44f401f20ab07b718))
90 | * memory leak for inline web workers ([#252](https://github.com/webpack-contrib/worker-loader/issues/252)) ([f729e34](https://github.com/webpack-contrib/worker-loader/commit/f729e342922180bf3b375a8d2ea6e1b72ca95d74))
91 | * source maps when `inline` using without fallback ([#269](https://github.com/webpack-contrib/worker-loader/issues/269)) ([5047abb](https://github.com/webpack-contrib/worker-loader/commit/5047abb2f9b97ff4706069716df8e718bee9de43))
92 | * the `publicPath` options works fine with async web workers chunks
93 | * compatibility with webpack@5 ([#259](https://github.com/webpack-contrib/worker-loader/issues/259)) ([e0d9887](https://github.com/webpack-contrib/worker-loader/commit/e0d98876c6ee83bc48ea9589b38437590878e9d9))
94 | * always use `self` as global object
95 | * compatibility with `webpack-dev-server`
96 | * increase performance
97 |
98 |
99 | ## [2.0.0](https://github.com/webpack-contrib/worker-loader/compare/v1.1.1...v2.0.0) (2018-05-27)
100 |
101 | ## Updates
102 |
103 | - refactor(index): remove `Tapable.apply` calls (#121)
104 | - docs: use ES6 import in TypeScript README example (#140) …
105 | - docs(README): add note about omitted hashes (`options.name`) (#131)
106 | - fix(package): homepage URL typo (#130)
107 |
108 | ## Breaking Changes
109 |
110 | Drops support for Webpack versions < 3.0.0
111 |
112 |
113 | ## [1.1.1](https://github.com/webpack-contrib/worker-loader/compare/v1.1.0...v1.1.1) (2018-02-25)
114 |
115 |
116 | ### Bug Fixes
117 |
118 | * **index:** add `webpack >= v4.0.0` support ([#128](https://github.com/webpack-contrib/worker-loader/issues/128)) ([d1a7a94](https://github.com/webpack-contrib/worker-loader/commit/d1a7a94))
119 |
120 |
121 |
122 |
123 | # [1.1.0](https://github.com/webpack-contrib/worker-loader/compare/v1.0.0...v1.1.0) (2017-10-24)
124 |
125 |
126 | ### Features
127 |
128 | * add `publicPath` support (`options.publicPath`) ([#31](https://github.com/webpack-contrib/worker-loader/issues/31)) ([96c6144](https://github.com/webpack-contrib/worker-loader/commit/96c6144))
129 |
130 |
131 |
132 |
133 | ## [1.0.0](https://github.com/webpack-contrib/worker-loader/compare/v0.8.0...v1.0.0) (2017-09-25)
134 |
135 |
136 | ### Features
137 |
138 | * add `options` validation (`schema-utils`) ([#78](https://github.com/webpack-contrib/worker-loader/issues/78)) ([5e2f5e6](https://github.com/webpack-contrib/worker-loader/commit/5e2f5e6))
139 | * support loading node core modules ([#76](https://github.com/webpack-contrib/worker-loader/issues/76)) ([edcda35](https://github.com/webpack-contrib/worker-loader/commit/edcda35))
140 |
141 |
142 | ### BREAKING CHANGES
143 |
144 | * loader-utils upgrade to > 1.0 is not backwards
145 | compatible with previous versions
146 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright JS Foundation and other contributors
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining
4 | a copy of this software and associated documentation files (the
5 | 'Software'), to deal in the Software without restriction, including
6 | without limitation the rights to use, copy, modify, merge, publish,
7 | distribute, sublicense, and/or sell copies of the Software, and to
8 | permit persons to whom the Software is furnished to do so, subject to
9 | the following conditions:
10 |
11 | The above copyright notice and this permission notice shall be
12 | included in all copies or substantial portions of the Software.
13 |
14 | THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
15 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
18 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
19 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
20 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
6 |
7 | [![npm][npm]][npm-url]
8 | [![node][node]][node-url]
9 | [![deps][deps]][deps-url]
10 | [![tests][tests]][tests-url]
11 | [![coverage][cover]][cover-url]
12 | [![chat][chat]][chat-url]
13 | [![size][size]][size-url]
14 |
15 | # worker-loader
16 |
17 | **DEPRECATED for v5**: https://webpack.js.org/guides/web-workers/
18 |
19 | Web Worker loader for webpack 4.
20 |
21 | Note that this is specific to webpack 4. To use Web Workers in webpack 5, see https://webpack.js.org/guides/web-workers/.
22 |
23 | ## Getting Started
24 |
25 | To begin, you'll need to install `worker-loader`:
26 |
27 | ```console
28 | $ npm install worker-loader --save-dev
29 | ```
30 |
31 | ### Inlined
32 |
33 | **App.js**
34 |
35 | ```js
36 | import Worker from "worker-loader!./Worker.js";
37 | ```
38 |
39 | ### Config
40 |
41 | **webpack.config.js**
42 |
43 | ```js
44 | module.exports = {
45 | module: {
46 | rules: [
47 | {
48 | test: /\.worker\.js$/,
49 | use: { loader: "worker-loader" },
50 | },
51 | ],
52 | },
53 | };
54 | ```
55 |
56 | **App.js**
57 |
58 | ```js
59 | import Worker from "./file.worker.js";
60 |
61 | const worker = new Worker();
62 |
63 | worker.postMessage({ a: 1 });
64 | worker.onmessage = function (event) {};
65 |
66 | worker.addEventListener("message", function (event) {});
67 | ```
68 |
69 | And run `webpack` via your preferred method.
70 |
71 | ## Options
72 |
73 | | Name | Type | Default | Description |
74 | | :-----------------------------------: | :-------------------------: | :-----------------------------: | :-------------------------------------------------------------------------------- |
75 | | **[`worker`](#worker)** | `{String\|Object}` | `Worker` | Allows to set web worker constructor name and options |
76 | | **[`publicPath`](#publicpath)** | `{String\|Function}` | based on `output.publicPath` | specifies the public URL address of the output files when referenced in a browser |
77 | | **[`filename`](#filename)** | `{String\|Function}` | based on `output.filename` | The filename of entry chunks for web workers |
78 | | **[`chunkFilename`](#chunkfilename)** | `{String}` | based on `output.chunkFilename` | The filename of non-entry chunks for web workers |
79 | | **[`inline`](#inline)** | `'no-fallback'\|'fallback'` | `undefined` | Allow to inline the worker as a `BLOB` |
80 | | **[`esModule`](#esmodule)** | `{Boolean}` | `true` | Use ES modules syntax |
81 |
82 | ### `worker`
83 |
84 | Type: `String|Object`
85 | Default: `Worker`
86 |
87 | Set the worker type.
88 |
89 | #### `String`
90 |
91 | Allows to set web worker constructor name.
92 |
93 | **webpack.config.js**
94 |
95 | ```js
96 | module.exports = {
97 | module: {
98 | rules: [
99 | {
100 | test: /\.worker\.(c|m)?js$/i,
101 | loader: "worker-loader",
102 | options: {
103 | worker: "SharedWorker",
104 | },
105 | },
106 | ],
107 | },
108 | };
109 | ```
110 |
111 | #### `Object`
112 |
113 | Allow to set web worker constructor name and options.
114 |
115 | **webpack.config.js**
116 |
117 | ```js
118 | module.exports = {
119 | module: {
120 | rules: [
121 | {
122 | test: /\.worker\.(c|m)?js$/i,
123 | loader: "worker-loader",
124 | options: {
125 | worker: {
126 | type: "SharedWorker",
127 | options: {
128 | type: "classic",
129 | credentials: "omit",
130 | name: "my-custom-worker-name",
131 | },
132 | },
133 | },
134 | },
135 | ],
136 | },
137 | };
138 | ```
139 |
140 | ### `publicPath`
141 |
142 | Type: `String|Function`
143 | Default: based on `output.publicPath`
144 |
145 | The `publicPath` specifies the public URL address of the output files when referenced in a browser.
146 | If not specified, the same public path used for other webpack assets is used.
147 |
148 | #### `String`
149 |
150 | **webpack.config.js**
151 |
152 | ```js
153 | module.exports = {
154 | module: {
155 | rules: [
156 | {
157 | test: /\.worker\.(c|m)?js$/i,
158 | loader: "worker-loader",
159 | options: {
160 | publicPath: "/scripts/workers/",
161 | },
162 | },
163 | ],
164 | },
165 | };
166 | ```
167 |
168 | #### `Function`
169 |
170 | **webpack.config.js**
171 |
172 | ```js
173 | module.exports = {
174 | module: {
175 | rules: [
176 | {
177 | test: /\.worker\.(c|m)?js$/i,
178 | loader: "worker-loader",
179 | options: {
180 | publicPath: (pathData, assetInfo) => {
181 | return `/scripts/${pathData.hash}/workers/`;
182 | },
183 | },
184 | },
185 | ],
186 | },
187 | };
188 | ```
189 |
190 | ### `filename`
191 |
192 | Type: `String|Function`
193 | Default: based on `output.filename`, adding `worker` suffix, for example - `output.filename: '[name].js'` value of this option will be `[name].worker.js`
194 |
195 | The filename of entry chunks for web workers.
196 |
197 | #### `String`
198 |
199 | **webpack.config.js**
200 |
201 | ```js
202 | module.exports = {
203 | module: {
204 | rules: [
205 | {
206 | test: /\.worker\.(c|m)?js$/i,
207 | loader: "worker-loader",
208 | options: {
209 | filename: "[name].[contenthash].worker.js",
210 | },
211 | },
212 | ],
213 | },
214 | };
215 | ```
216 |
217 | #### `Function`
218 |
219 | **webpack.config.js**
220 |
221 | ```js
222 | module.exports = {
223 | module: {
224 | rules: [
225 | {
226 | test: /\.worker\.(c|m)?js$/i,
227 | loader: "worker-loader",
228 | options: {
229 | filename: (pathData) => {
230 | if (
231 | /\.worker\.(c|m)?js$/i.test(pathData.chunk.entryModule.resource)
232 | ) {
233 | return "[name].custom.worker.js";
234 | }
235 |
236 | return "[name].js";
237 | },
238 | },
239 | },
240 | ],
241 | },
242 | };
243 | ```
244 |
245 | ### `chunkFilename`
246 |
247 | Type: `String`
248 | Default: based on `output.chunkFilename`, adding `worker` suffix, for example - `output.chunkFilename: '[id].js'` value of this option will be `[id].worker.js`
249 |
250 | The filename of non-entry chunks for web workers.
251 |
252 | **webpack.config.js**
253 |
254 | ```js
255 | module.exports = {
256 | module: {
257 | rules: [
258 | {
259 | test: /\.worker\.(c|m)?js$/i,
260 | loader: "worker-loader",
261 | options: {
262 | chunkFilename: "[id].[contenthash].worker.js",
263 | },
264 | },
265 | ],
266 | },
267 | };
268 | ```
269 |
270 | ### `inline`
271 |
272 | Type: `'fallback' | 'no-fallback'`
273 | Default: `undefined`
274 |
275 | Allow to inline the worker as a `BLOB`.
276 |
277 | Inline mode with the `fallback` value will create file for browsers without support web workers, to disable this behavior just use `no-fallback` value.
278 |
279 | **webpack.config.js**
280 |
281 | ```js
282 | module.exports = {
283 | module: {
284 | rules: [
285 | {
286 | test: /\.worker\.(c|m)?js$/i,
287 | loader: "worker-loader",
288 | options: {
289 | inline: "fallback",
290 | },
291 | },
292 | ],
293 | },
294 | };
295 | ```
296 |
297 | ### `esModule`
298 |
299 | Type: `Boolean`
300 | Default: `true`
301 |
302 | By default, `worker-loader` generates JS modules that use the ES modules syntax.
303 |
304 | You can enable a CommonJS modules syntax using:
305 |
306 | **webpack.config.js**
307 |
308 | ```js
309 | module.exports = {
310 | module: {
311 | rules: [
312 | {
313 | test: /\.worker\.(c|m)?js$/i,
314 | loader: "worker-loader",
315 | options: {
316 | esModule: false,
317 | },
318 | },
319 | ],
320 | },
321 | };
322 | ```
323 |
324 | ## Examples
325 |
326 | ### Basic
327 |
328 | The worker file can import dependencies just like any other file:
329 |
330 | **index.js**
331 |
332 | ```js
333 | import Worker from "./my.worker.js";
334 |
335 | var worker = new Worker();
336 |
337 | var result;
338 |
339 | worker.onmessage = function (event) {
340 | if (!result) {
341 | result = document.createElement("div");
342 | result.setAttribute("id", "result");
343 |
344 | document.body.append(result);
345 | }
346 |
347 | result.innerText = JSON.stringify(event.data);
348 | };
349 |
350 | const button = document.getElementById("button");
351 |
352 | button.addEventListener("click", function () {
353 | worker.postMessage({ postMessage: true });
354 | });
355 | ```
356 |
357 | **my.worker.js**
358 |
359 | ```js
360 | onmessage = function (event) {
361 | var workerResult = event.data;
362 |
363 | workerResult.onmessage = true;
364 |
365 | postMessage(workerResult);
366 | };
367 | ```
368 |
369 | **webpack.config.js**
370 |
371 | ```js
372 | module.exports = {
373 | module: {
374 | rules: [
375 | {
376 | test: /\.worker\.(c|m)?js$/i,
377 | loader: "worker-loader",
378 | options: {
379 | esModule: false,
380 | },
381 | },
382 | ],
383 | },
384 | };
385 | ```
386 |
387 | ### Integrating with ES6+ features
388 |
389 | You can even use ES6+ features if you have the [`babel-loader`](https://github.com/babel/babel-loader) configured.
390 |
391 | **index.js**
392 |
393 | ```js
394 | import Worker from "./my.worker.js";
395 |
396 | const worker = new Worker();
397 |
398 | let result;
399 |
400 | worker.onmessage = (event) => {
401 | if (!result) {
402 | result = document.createElement("div");
403 | result.setAttribute("id", "result");
404 |
405 | document.body.append(result);
406 | }
407 |
408 | result.innerText = JSON.stringify(event.data);
409 | };
410 |
411 | const button = document.getElementById("button");
412 |
413 | button.addEventListener("click", () => {
414 | worker.postMessage({ postMessage: true });
415 | });
416 | ```
417 |
418 | **my.worker.js**
419 |
420 | ```js
421 | onmessage = function (event) {
422 | const workerResult = event.data;
423 |
424 | workerResult.onmessage = true;
425 |
426 | postMessage(workerResult);
427 | };
428 | ```
429 |
430 | **webpack.config.js**
431 |
432 | ```js
433 | module.exports = {
434 | module: {
435 | rules: [
436 | {
437 | test: /\.worker\.(c|m)?js$/i,
438 | use: [
439 | {
440 | loader: "worker-loader",
441 | },
442 | {
443 | loader: "babel-loader",
444 | options: {
445 | presets: ["@babel/preset-env"],
446 | },
447 | },
448 | ],
449 | },
450 | ],
451 | },
452 | };
453 | ```
454 |
455 | ### Integrating with TypeScript
456 |
457 | To integrate with TypeScript, you will need to define a custom module for the exports of your worker.
458 |
459 | #### Loading with `worker-loader!`
460 |
461 | **typings/worker-loader.d.ts**
462 |
463 | ```typescript
464 | declare module "worker-loader!*" {
465 | // You need to change `Worker`, if you specified a different value for the `workerType` option
466 | class WebpackWorker extends Worker {
467 | constructor();
468 | }
469 |
470 | // Uncomment this if you set the `esModule` option to `false`
471 | // export = WebpackWorker;
472 | export default WebpackWorker;
473 | }
474 | ```
475 |
476 | **my.worker.ts**
477 |
478 | ```typescript
479 | const ctx: Worker = self as any;
480 |
481 | // Post data to parent thread
482 | ctx.postMessage({ foo: "foo" });
483 |
484 | // Respond to message from parent thread
485 | ctx.addEventListener("message", (event) => console.log(event));
486 | ```
487 |
488 | **index.ts**
489 |
490 | ```typescript
491 | import Worker from "worker-loader!./Worker";
492 |
493 | const worker = new Worker();
494 |
495 | worker.postMessage({ a: 1 });
496 | worker.onmessage = (event) => {};
497 |
498 | worker.addEventListener("message", (event) => {});
499 | ```
500 |
501 | #### Loading without `worker-loader!`
502 |
503 | Alternatively, you can omit the `worker-loader!` prefix passed to `import` statement by using the following notation.
504 | This is useful for executing the code using a non-WebPack runtime environment
505 | (such as Jest with [`workerloader-jest-transformer`](https://github.com/astagi/workerloader-jest-transformer)).
506 |
507 | **typings/worker-loader.d.ts**
508 |
509 | ```typescript
510 | declare module "*.worker.ts" {
511 | // You need to change `Worker`, if you specified a different value for the `workerType` option
512 | class WebpackWorker extends Worker {
513 | constructor();
514 | }
515 |
516 | // Uncomment this if you set the `esModule` option to `false`
517 | // export = WebpackWorker;
518 | export default WebpackWorker;
519 | }
520 | ```
521 |
522 | **my.worker.ts**
523 |
524 | ```typescript
525 | const ctx: Worker = self as any;
526 |
527 | // Post data to parent thread
528 | ctx.postMessage({ foo: "foo" });
529 |
530 | // Respond to message from parent thread
531 | ctx.addEventListener("message", (event) => console.log(event));
532 | ```
533 |
534 | **index.ts**
535 |
536 | ```typescript
537 | import MyWorker from "./my.worker.ts";
538 |
539 | const worker = new MyWorker();
540 |
541 | worker.postMessage({ a: 1 });
542 | worker.onmessage = (event) => {};
543 |
544 | worker.addEventListener("message", (event) => {});
545 | ```
546 |
547 | **webpack.config.js**
548 |
549 | ```js
550 | module.exports = {
551 | module: {
552 | rules: [
553 | // Place this *before* the `ts-loader`.
554 | {
555 | test: /\.worker\.ts$/,
556 | loader: "worker-loader",
557 | },
558 | {
559 | test: /\.ts$/,
560 | loader: "ts-loader",
561 | },
562 | ],
563 | },
564 | resolve: {
565 | extensions: [".ts", ".js"],
566 | },
567 | };
568 | ```
569 |
570 | ### Cross-Origin Policy
571 |
572 | [`WebWorkers`](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) are restricted by a [same-origin policy](https://en.wikipedia.org/wiki/Same-origin_policy), so if your `webpack` assets are not being served from the same origin as your application, their download may be blocked by your browser.
573 | This scenario can commonly occur if you are hosting your assets under a CDN domain.
574 | Even downloads from the `webpack-dev-server` could be blocked.
575 |
576 | There are two workarounds:
577 |
578 | Firstly, you can inline the worker as a blob instead of downloading it as an external script via the [`inline`](#inline) parameter
579 |
580 | **App.js**
581 |
582 | ```js
583 | import Worker from "./file.worker.js";
584 | ```
585 |
586 | **webpack.config.js**
587 |
588 | ```js
589 | module.exports = {
590 | module: {
591 | rules: [
592 | {
593 | loader: "worker-loader",
594 | options: { inline: "fallback" },
595 | },
596 | ],
597 | },
598 | };
599 | ```
600 |
601 | Secondly, you may override the base download URL for your worker script via the [`publicPath`](#publicpath) option
602 |
603 | **App.js**
604 |
605 | ```js
606 | // This will cause the worker to be downloaded from `/workers/file.worker.js`
607 | import Worker from "./file.worker.js";
608 | ```
609 |
610 | **webpack.config.js**
611 |
612 | ```js
613 | module.exports = {
614 | module: {
615 | rules: [
616 | {
617 | loader: "worker-loader",
618 | options: { publicPath: "/workers/" },
619 | },
620 | ],
621 | },
622 | };
623 | ```
624 |
625 | ## Contributing
626 |
627 | Please take a moment to read our contributing guidelines if you haven't yet done so.
628 |
629 | [CONTRIBUTING](./.github/CONTRIBUTING.md)
630 |
631 | ## License
632 |
633 | [MIT](./LICENSE)
634 |
635 | [npm]: https://img.shields.io/npm/v/worker-loader.svg
636 | [npm-url]: https://npmjs.com/package/worker-loader
637 | [node]: https://img.shields.io/node/v/worker-loader.svg
638 | [node-url]: https://nodejs.org
639 | [deps]: https://david-dm.org/webpack-contrib/worker-loader.svg
640 | [deps-url]: https://david-dm.org/webpack-contrib/worker-loader
641 | [tests]: https://github.com/webpack-contrib/worker-loader/workflows/worker-loader/badge.svg
642 | [tests-url]: https://github.com/webpack-contrib/worker-loader/actions
643 | [cover]: https://codecov.io/gh/webpack-contrib/worker-loader/branch/master/graph/badge.svg
644 | [cover-url]: https://codecov.io/gh/webpack-contrib/worker-loader
645 | [chat]: https://badges.gitter.im/webpack/webpack.svg
646 | [chat-url]: https://gitter.im/webpack/webpack
647 | [size]: https://packagephobia.now.sh/badge?p=worker-loader
648 | [size-url]: https://packagephobia.now.sh/result?p=worker-loader
649 |
--------------------------------------------------------------------------------
/babel.config.js:
--------------------------------------------------------------------------------
1 | const MIN_BABEL_VERSION = 7;
2 |
3 | module.exports = (api) => {
4 | api.assertVersion(MIN_BABEL_VERSION);
5 | api.cache(true);
6 |
7 | return {
8 | presets: [
9 | [
10 | "@babel/preset-env",
11 | {
12 | targets: {
13 | node: "10.13.0",
14 | },
15 | },
16 | ],
17 | ],
18 | overrides: [
19 | {
20 | test: "./src/runtime",
21 | presets: [
22 | [
23 | "@babel/preset-env",
24 | {
25 | targets: {
26 | node: "0.12",
27 | },
28 | },
29 | ],
30 | ],
31 | },
32 | ],
33 | };
34 | };
35 |
--------------------------------------------------------------------------------
/commitlint.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | extends: ["@commitlint/config-conventional"],
3 | };
4 |
--------------------------------------------------------------------------------
/globalSetupTest.js:
--------------------------------------------------------------------------------
1 | import path from "path";
2 |
3 | // eslint-disable-next-line import/no-extraneous-dependencies
4 | import del from "del";
5 |
6 | async function setup() {
7 | await del(path.resolve(__dirname, `./test/outputs`));
8 | }
9 |
10 | module.exports = setup;
11 |
--------------------------------------------------------------------------------
/husky.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | hooks: {
3 | "pre-commit": "lint-staged",
4 | "commit-msg": "commitlint -E HUSKY_GIT_PARAMS",
5 | },
6 | };
7 |
--------------------------------------------------------------------------------
/jest.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | testEnvironment: "node",
3 | globalSetup: "/globalSetupTest.js",
4 | setupFilesAfterEnv: ["/setupTest.js"],
5 | };
6 |
--------------------------------------------------------------------------------
/lint-staged.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | "*.js": ["eslint --fix", "prettier --write"],
3 | "*.{json,md,yml,css,ts}": ["prettier --write"],
4 | };
5 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "worker-loader",
3 | "version": "3.0.8",
4 | "description": "worker loader module for webpack",
5 | "license": "MIT",
6 | "repository": "webpack-contrib/worker-loader",
7 | "author": "Tobias Koppers @sokra",
8 | "homepage": "https://github.com/webpack-contrib/worker-loader",
9 | "bugs": "https://github.com/webpack-contrib/worker-loader/issues",
10 | "funding": {
11 | "type": "opencollective",
12 | "url": "https://opencollective.com/webpack"
13 | },
14 | "main": "dist/cjs.js",
15 | "engines": {
16 | "node": ">= 10.13.0"
17 | },
18 | "scripts": {
19 | "start": "npm run build -- -w",
20 | "clean": "del-cli dist",
21 | "prebuild": "npm run clean",
22 | "build": "cross-env NODE_ENV=production babel src -d dist --copy-files",
23 | "commitlint": "commitlint --from=master",
24 | "security": "npm audit",
25 | "lint:prettier": "prettier --list-different .",
26 | "lint:js": "eslint --cache .",
27 | "lint": "npm-run-all -l -p \"lint:**\"",
28 | "test:only": "cross-env NODE_ENV=test jest",
29 | "test:watch": "npm run test:only -- --watch",
30 | "test:coverage": "npm run test:only -- --collectCoverageFrom=\"src/**/*.js\" --coverage",
31 | "pretest": "npm run lint",
32 | "test": "npm run test:coverage",
33 | "prepare": "npm run build",
34 | "release": "standard-version"
35 | },
36 | "files": [
37 | "dist"
38 | ],
39 | "peerDependencies": {
40 | "webpack": "^4.0.0 || ^5.0.0"
41 | },
42 | "dependencies": {
43 | "loader-utils": "^2.0.0",
44 | "schema-utils": "^3.1.0"
45 | },
46 | "devDependencies": {
47 | "@babel/cli": "^7.14.5",
48 | "@babel/core": "^7.14.6",
49 | "@babel/preset-env": "^7.14.7",
50 | "@commitlint/cli": "^12.1.4",
51 | "@commitlint/config-conventional": "^12.1.4",
52 | "@webpack-contrib/eslint-config-webpack": "^3.0.0",
53 | "babel-jest": "^26.6.3",
54 | "cross-env": "^7.0.3",
55 | "del": "^6.0.0",
56 | "del-cli": "^3.0.1",
57 | "eslint": "^7.31.0",
58 | "eslint-config-prettier": "^8.3.0",
59 | "eslint-plugin-import": "^2.23.4",
60 | "express": "^4.17.1",
61 | "get-port": "^5.1.1",
62 | "html-webpack-plugin": "^4.5.0",
63 | "husky": "^4.3.0",
64 | "jest": "^26.6.3",
65 | "lint-staged": "^10.5.4",
66 | "memfs": "^3.2.0",
67 | "nanoid": "^3.1.20",
68 | "npm-run-all": "^4.1.5",
69 | "prettier": "^2.3.2",
70 | "puppeteer": "^7.0.4",
71 | "standard-version": "^9.3.1",
72 | "webpack": "^5.45.1"
73 | },
74 | "keywords": [
75 | "webpack"
76 | ],
77 | "jest": {
78 | "testEnvironment": "node"
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/setupTest.js:
--------------------------------------------------------------------------------
1 | jest.setTimeout(90000);
2 |
--------------------------------------------------------------------------------
/src/cjs.js:
--------------------------------------------------------------------------------
1 | const loader = require("./index");
2 |
3 | module.exports = loader.default;
4 | module.exports.pitch = loader.pitch;
5 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | import path from "path";
2 |
3 | import { getOptions } from "loader-utils";
4 | import { validate } from "schema-utils";
5 |
6 | import NodeTargetPlugin from "webpack/lib/node/NodeTargetPlugin";
7 | import SingleEntryPlugin from "webpack/lib/SingleEntryPlugin";
8 | import WebWorkerTemplatePlugin from "webpack/lib/webworker/WebWorkerTemplatePlugin";
9 | import ExternalsPlugin from "webpack/lib/ExternalsPlugin";
10 |
11 | import schema from "./options.json";
12 | import supportWebpack5 from "./supportWebpack5";
13 | import supportWebpack4 from "./supportWebpack4";
14 | import {
15 | getDefaultFilename,
16 | getDefaultChunkFilename,
17 | getExternalsType,
18 | } from "./utils";
19 |
20 | let FetchCompileWasmPlugin;
21 | let FetchCompileAsyncWasmPlugin;
22 |
23 | // determine the version of webpack peer dependency
24 | // eslint-disable-next-line global-require, import/no-unresolved
25 | const useWebpack5 = require("webpack/package.json").version.startsWith("5.");
26 |
27 | if (useWebpack5) {
28 | // eslint-disable-next-line global-require, import/no-unresolved
29 | FetchCompileWasmPlugin = require("webpack/lib/web/FetchCompileWasmPlugin");
30 | // eslint-disable-next-line global-require, import/no-unresolved
31 | FetchCompileAsyncWasmPlugin = require("webpack/lib/web/FetchCompileAsyncWasmPlugin");
32 | } else {
33 | // eslint-disable-next-line global-require, import/no-unresolved, import/extensions
34 | FetchCompileWasmPlugin = require("webpack/lib/web/FetchCompileWasmTemplatePlugin");
35 | }
36 |
37 | export default function loader() {}
38 |
39 | export function pitch(request) {
40 | this.cacheable(false);
41 |
42 | const options = getOptions(this);
43 |
44 | validate(schema, options, {
45 | name: "Worker Loader",
46 | baseDataPath: "options",
47 | });
48 |
49 | const workerContext = {};
50 | const compilerOptions = this._compiler.options || {};
51 | const filename = options.filename
52 | ? options.filename
53 | : getDefaultFilename(compilerOptions.output.filename);
54 | const chunkFilename = options.chunkFilename
55 | ? options.chunkFilename
56 | : getDefaultChunkFilename(compilerOptions.output.chunkFilename);
57 | const publicPath = options.publicPath
58 | ? options.publicPath
59 | : compilerOptions.output.publicPath;
60 |
61 | workerContext.options = {
62 | filename,
63 | chunkFilename,
64 | publicPath,
65 | globalObject: "self",
66 | };
67 |
68 | workerContext.compiler = this._compilation.createChildCompiler(
69 | `worker-loader ${request}`,
70 | workerContext.options
71 | );
72 |
73 | new WebWorkerTemplatePlugin().apply(workerContext.compiler);
74 |
75 | if (this.target !== "webworker" && this.target !== "web") {
76 | new NodeTargetPlugin().apply(workerContext.compiler);
77 | }
78 |
79 | if (FetchCompileWasmPlugin) {
80 | new FetchCompileWasmPlugin({
81 | mangleImports: compilerOptions.optimization.mangleWasmImports,
82 | }).apply(workerContext.compiler);
83 | }
84 |
85 | if (FetchCompileAsyncWasmPlugin) {
86 | new FetchCompileAsyncWasmPlugin().apply(workerContext.compiler);
87 | }
88 |
89 | if (compilerOptions.externals) {
90 | new ExternalsPlugin(
91 | getExternalsType(compilerOptions),
92 | compilerOptions.externals
93 | ).apply(workerContext.compiler);
94 | }
95 |
96 | new SingleEntryPlugin(
97 | this.context,
98 | `!!${request}`,
99 | path.parse(this.resourcePath).name
100 | ).apply(workerContext.compiler);
101 |
102 | workerContext.request = request;
103 |
104 | const cb = this.async();
105 |
106 | if (
107 | workerContext.compiler.cache &&
108 | typeof workerContext.compiler.cache.get === "function"
109 | ) {
110 | supportWebpack5(this, workerContext, options, cb);
111 | } else {
112 | supportWebpack4(this, workerContext, options, cb);
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/src/options.json:
--------------------------------------------------------------------------------
1 | {
2 | "type": "object",
3 | "properties": {
4 | "worker": {
5 | "anyOf": [
6 | {
7 | "type": "string",
8 | "minLength": 1
9 | },
10 | {
11 | "type": "object",
12 | "additionalProperties": false,
13 | "properties": {
14 | "type": {
15 | "type": "string",
16 | "minLength": 1
17 | },
18 | "options": {
19 | "additionalProperties": true,
20 | "type": "object"
21 | }
22 | },
23 | "required": ["type"]
24 | }
25 | ],
26 | "description": "Set the worker type.",
27 | "link": "https://github.com/webpack-contrib/worker-loader#worker"
28 | },
29 | "publicPath": {
30 | "anyOf": [
31 | {
32 | "type": "string"
33 | },
34 | {
35 | "instanceof": "Function"
36 | }
37 | ],
38 | "description": "Specifies the public URL address of the output files when referenced in a browser.",
39 | "link": "https://github.com/webpack-contrib/worker-loader#publicpath"
40 | },
41 | "filename": {
42 | "anyOf": [
43 | {
44 | "type": "string",
45 | "minLength": 1
46 | },
47 | {
48 | "instanceof": "Function"
49 | }
50 | ],
51 | "description": "The filename of entry chunks for web workers.",
52 | "link": "https://github.com/webpack-contrib/worker-loader#filename"
53 | },
54 | "chunkFilename": {
55 | "type": "string",
56 | "description": "The filename of non-entry chunks for web workers.",
57 | "link": "https://github.com/webpack-contrib/worker-loader#chunkfilename",
58 | "minLength": 1
59 | },
60 | "inline": {
61 | "enum": ["no-fallback", "fallback"],
62 | "description": "Allow to inline the worker as a BLOB.",
63 | "link": "https://github.com/webpack-contrib/worker-loader#inline"
64 | },
65 | "esModule": {
66 | "type": "boolean",
67 | "description": "Enable or disable ES module syntax.",
68 | "link": "https://github.com/webpack-contrib/worker-loader#esmodule"
69 | }
70 | },
71 | "additionalProperties": false
72 | }
73 |
--------------------------------------------------------------------------------
/src/runtime/inline.js:
--------------------------------------------------------------------------------
1 | /* eslint-env browser */
2 | /* eslint-disable no-undef, no-use-before-define, new-cap */
3 |
4 | module.exports = (content, workerConstructor, workerOptions, url) => {
5 | const globalScope = self || window;
6 | try {
7 | try {
8 | let blob;
9 |
10 | try {
11 | // New API
12 | blob = new globalScope.Blob([content]);
13 | } catch (e) {
14 | // BlobBuilder = Deprecated, but widely implemented
15 | const BlobBuilder =
16 | globalScope.BlobBuilder ||
17 | globalScope.WebKitBlobBuilder ||
18 | globalScope.MozBlobBuilder ||
19 | globalScope.MSBlobBuilder;
20 |
21 | blob = new BlobBuilder();
22 |
23 | blob.append(content);
24 |
25 | blob = blob.getBlob();
26 | }
27 |
28 | const URL = globalScope.URL || globalScope.webkitURL;
29 | const objectURL = URL.createObjectURL(blob);
30 | const worker = new globalScope[workerConstructor](
31 | objectURL,
32 | workerOptions
33 | );
34 |
35 | URL.revokeObjectURL(objectURL);
36 |
37 | return worker;
38 | } catch (e) {
39 | return new globalScope[workerConstructor](
40 | `data:application/javascript,${encodeURIComponent(content)}`,
41 | workerOptions
42 | );
43 | }
44 | } catch (e) {
45 | if (!url) {
46 | throw Error("Inline worker is not supported");
47 | }
48 |
49 | return new globalScope[workerConstructor](url, workerOptions);
50 | }
51 | };
52 |
--------------------------------------------------------------------------------
/src/supportWebpack4.js:
--------------------------------------------------------------------------------
1 | import {
2 | workerGenerator,
3 | sourceMappingURLRegex,
4 | sourceURLWebpackRegex,
5 | } from "./utils";
6 |
7 | export default function runAsChild(
8 | loaderContext,
9 | workerContext,
10 | options,
11 | callback
12 | ) {
13 | workerContext.compiler.runAsChild((error, entries, compilation) => {
14 | if (error) {
15 | return callback(error);
16 | }
17 |
18 | if (entries[0]) {
19 | // eslint-disable-next-line no-param-reassign, prefer-destructuring
20 | const workerFilename = entries[0].files[0];
21 |
22 | let workerSource = compilation.assets[workerFilename].source();
23 |
24 | if (options.inline === "no-fallback") {
25 | // eslint-disable-next-line no-underscore-dangle, no-param-reassign
26 | delete loaderContext._compilation.assets[workerFilename];
27 |
28 | // TODO improve it, we should store generated source maps files for file in `assetInfo`
29 | // eslint-disable-next-line no-underscore-dangle
30 | if (loaderContext._compilation.assets[`${workerFilename}.map`]) {
31 | // eslint-disable-next-line no-underscore-dangle, no-param-reassign
32 | delete loaderContext._compilation.assets[`${workerFilename}.map`];
33 | }
34 |
35 | // Remove `/* sourceMappingURL=url */` comment
36 | workerSource = workerSource.replace(sourceMappingURLRegex, "");
37 |
38 | // Remove `//# sourceURL=webpack-internal` comment
39 | workerSource = workerSource.replace(sourceURLWebpackRegex, "");
40 | }
41 |
42 | const workerCode = workerGenerator(
43 | loaderContext,
44 | workerFilename,
45 | workerSource,
46 | options
47 | );
48 |
49 | return callback(null, workerCode);
50 | }
51 |
52 | return callback(
53 | new Error(
54 | `Failed to compile web worker "${workerContext.request}" request`
55 | )
56 | );
57 | });
58 | }
59 |
--------------------------------------------------------------------------------
/src/supportWebpack5.js:
--------------------------------------------------------------------------------
1 | import {
2 | workerGenerator,
3 | sourceMappingURLRegex,
4 | sourceURLWebpackRegex,
5 | } from "./utils";
6 |
7 | export default function runAsChild(
8 | loaderContext,
9 | workerContext,
10 | options,
11 | callback
12 | ) {
13 | workerContext.compiler.runAsChild((error, entries, compilation) => {
14 | if (error) {
15 | return callback(error);
16 | }
17 |
18 | if (entries[0]) {
19 | const [workerFilename] = [...entries[0].files];
20 | const cache = workerContext.compiler.getCache("worker-loader");
21 | const cacheIdent = workerFilename;
22 | const cacheETag = cache.getLazyHashedEtag(
23 | compilation.assets[workerFilename]
24 | );
25 |
26 | return cache.get(cacheIdent, cacheETag, (getCacheError, content) => {
27 | if (getCacheError) {
28 | return callback(getCacheError);
29 | }
30 |
31 | if (options.inline === "no-fallback") {
32 | // eslint-disable-next-line no-underscore-dangle, no-param-reassign
33 | delete loaderContext._compilation.assets[workerFilename];
34 |
35 | // TODO improve this, we should store generated source maps files for file in `assetInfo`
36 | // eslint-disable-next-line no-underscore-dangle
37 | if (loaderContext._compilation.assets[`${workerFilename}.map`]) {
38 | // eslint-disable-next-line no-underscore-dangle, no-param-reassign
39 | delete loaderContext._compilation.assets[`${workerFilename}.map`];
40 | }
41 | }
42 |
43 | if (content) {
44 | return callback(null, content);
45 | }
46 |
47 | let workerSource = compilation.assets[workerFilename].source();
48 |
49 | if (options.inline === "no-fallback") {
50 | // Remove `/* sourceMappingURL=url */` comment
51 | workerSource = workerSource.replace(sourceMappingURLRegex, "");
52 |
53 | // Remove `//# sourceURL=webpack-internal` comment
54 | workerSource = workerSource.replace(sourceURLWebpackRegex, "");
55 | }
56 |
57 | const workerCode = workerGenerator(
58 | loaderContext,
59 | workerFilename,
60 | workerSource,
61 | options
62 | );
63 | const workerCodeBuffer = Buffer.from(workerCode);
64 |
65 | return cache.store(
66 | cacheIdent,
67 | cacheETag,
68 | workerCodeBuffer,
69 | (storeCacheError) => {
70 | if (storeCacheError) {
71 | return callback(storeCacheError);
72 | }
73 |
74 | return callback(null, workerCodeBuffer);
75 | }
76 | );
77 | });
78 | }
79 |
80 | return callback(
81 | new Error(
82 | `Failed to compile web worker "${workerContext.request}" request`
83 | )
84 | );
85 | });
86 | }
87 |
--------------------------------------------------------------------------------
/src/utils.js:
--------------------------------------------------------------------------------
1 | import { stringifyRequest } from "loader-utils";
2 |
3 | function getDefaultFilename(filename) {
4 | if (typeof filename === "function") {
5 | return filename;
6 | }
7 |
8 | return filename.replace(/\.([a-z]+)(\?.+)?$/i, ".worker.$1$2");
9 | }
10 |
11 | function getDefaultChunkFilename(chunkFilename) {
12 | return chunkFilename.replace(/\.([a-z]+)(\?.+)?$/i, ".worker.$1$2");
13 | }
14 |
15 | function getExternalsType(compilerOptions) {
16 | // For webpack@4
17 | if (compilerOptions.output.libraryTarget) {
18 | return compilerOptions.output.libraryTarget;
19 | }
20 |
21 | // For webpack@5
22 | if (compilerOptions.externalsType) {
23 | return compilerOptions.externalsType;
24 | }
25 |
26 | if (compilerOptions.output.library) {
27 | return compilerOptions.output.library.type;
28 | }
29 |
30 | if (compilerOptions.output.module) {
31 | return "module";
32 | }
33 |
34 | return "var";
35 | }
36 |
37 | function workerGenerator(loaderContext, workerFilename, workerSource, options) {
38 | let workerConstructor;
39 | let workerOptions;
40 |
41 | if (typeof options.worker === "undefined") {
42 | workerConstructor = "Worker";
43 | } else if (typeof options.worker === "string") {
44 | workerConstructor = options.worker;
45 | } else {
46 | ({ type: workerConstructor, options: workerOptions } = options.worker);
47 | }
48 |
49 | const esModule =
50 | typeof options.esModule !== "undefined" ? options.esModule : true;
51 | const fnName = `${workerConstructor}_fn`;
52 |
53 | if (options.inline) {
54 | const InlineWorkerPath = stringifyRequest(
55 | loaderContext,
56 | `!!${require.resolve("./runtime/inline.js")}`
57 | );
58 |
59 | let fallbackWorkerPath;
60 |
61 | if (options.inline === "fallback") {
62 | fallbackWorkerPath = `__webpack_public_path__ + ${JSON.stringify(
63 | workerFilename
64 | )}`;
65 | }
66 |
67 | return `
68 | ${
69 | esModule
70 | ? `import worker from ${InlineWorkerPath};`
71 | : `var worker = require(${InlineWorkerPath});`
72 | }
73 |
74 | ${
75 | esModule ? "export default" : "module.exports ="
76 | } function ${fnName}() {\n return worker(${JSON.stringify(
77 | workerSource
78 | )}, ${JSON.stringify(workerConstructor)}, ${JSON.stringify(
79 | workerOptions
80 | )}, ${fallbackWorkerPath});\n}\n`;
81 | }
82 |
83 | return `${
84 | esModule ? "export default" : "module.exports ="
85 | } function ${fnName}() {\n return new ${workerConstructor}(__webpack_public_path__ + ${JSON.stringify(
86 | workerFilename
87 | )}${workerOptions ? `, ${JSON.stringify(workerOptions)}` : ""});\n}\n`;
88 | }
89 |
90 | // Matches only the last occurrence of sourceMappingURL
91 | const innerRegex =
92 | /\s*[#@]\s*sourceMappingURL\s*=\s*(.*?(?=[\s'"]|\\n|\*\/|$)(?:\\n)?)\s*/;
93 |
94 | /* eslint-disable prefer-template */
95 | const sourceMappingURLRegex = RegExp(
96 | "(?:" +
97 | "/\\*" +
98 | "(?:\\s*\r?\n(?://)?)?" +
99 | "(?:" +
100 | innerRegex.source +
101 | ")" +
102 | "\\s*" +
103 | "\\*/" +
104 | "|" +
105 | "//(?:" +
106 | innerRegex.source +
107 | ")" +
108 | ")" +
109 | "\\s*"
110 | );
111 |
112 | const sourceURLWebpackRegex = RegExp(
113 | "\\/\\/#\\ssourceURL=webpack-internal:\\/\\/\\/(.*?)\\\\n"
114 | );
115 | /* eslint-enable prefer-template */
116 |
117 | export {
118 | getDefaultFilename,
119 | getDefaultChunkFilename,
120 | getExternalsType,
121 | workerGenerator,
122 | sourceMappingURLRegex,
123 | sourceURLWebpackRegex,
124 | };
125 |
--------------------------------------------------------------------------------
/test/__snapshots__/chunkFilename-option.test.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`"name" option should chunkFilename suffix be inserted before query parameters: errors 1`] = `Array []`;
4 |
5 | exports[`"name" option should chunkFilename suffix be inserted before query parameters: module 1`] = `
6 | "export default function Worker_fn() {
7 | return new Worker(__webpack_public_path__ + \\"worker.worker.js\\");
8 | }
9 | "
10 | `;
11 |
12 | exports[`"name" option should chunkFilename suffix be inserted before query parameters: result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
13 |
14 | exports[`"name" option should chunkFilename suffix be inserted before query parameters: result 2`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
15 |
16 | exports[`"name" option should chunkFilename suffix be inserted before query parameters: warnings 1`] = `Array []`;
17 |
18 | exports[`"name" option should work ("string"): errors 1`] = `Array []`;
19 |
20 | exports[`"name" option should work ("string"): module 1`] = `
21 | "export default function Worker_fn() {
22 | return new Worker(__webpack_public_path__ + \\"test.worker.js\\");
23 | }
24 | "
25 | `;
26 |
27 | exports[`"name" option should work ("string"): result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
28 |
29 | exports[`"name" option should work ("string"): warnings 1`] = `Array []`;
30 |
31 | exports[`"name" option should work and respect the "output.chunkFilename" default value option: errors 1`] = `Array []`;
32 |
33 | exports[`"name" option should work and respect the "output.chunkFilename" default value option: module 1`] = `
34 | "export default function Worker_fn() {
35 | return new Worker(__webpack_public_path__ + \\"worker.worker.js\\");
36 | }
37 | "
38 | `;
39 |
40 | exports[`"name" option should work and respect the "output.chunkFilename" default value option: result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
41 |
42 | exports[`"name" option should work and respect the "output.chunkFilename" default value option: warnings 1`] = `Array []`;
43 |
44 | exports[`"name" option should work and respect the "output.chunkFilename" option ("string"): errors 1`] = `Array []`;
45 |
46 | exports[`"name" option should work and respect the "output.chunkFilename" option ("string"): module 1`] = `
47 | "export default function Worker_fn() {
48 | return new Worker(__webpack_public_path__ + \\"worker.worker.js\\");
49 | }
50 | "
51 | `;
52 |
53 | exports[`"name" option should work and respect the "output.chunkFilename" option ("string"): result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
54 |
55 | exports[`"name" option should work and respect the "output.chunkFilename" option ("string"): warnings 1`] = `Array []`;
56 |
--------------------------------------------------------------------------------
/test/__snapshots__/esModule-option.test.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`"esModule" option should work and generate ES module syntax by default: errors 1`] = `Array []`;
4 |
5 | exports[`"esModule" option should work and generate ES module syntax by default: module 1`] = `
6 | "export default function Worker_fn() {
7 | return new Worker(__webpack_public_path__ + \\"test.worker.js\\");
8 | }
9 | "
10 | `;
11 |
12 | exports[`"esModule" option should work and generate ES module syntax by default: warnings 1`] = `Array []`;
13 |
14 | exports[`"esModule" option should work with "false" value: errors 1`] = `Array []`;
15 |
16 | exports[`"esModule" option should work with "false" value: module 1`] = `
17 | "module.exports = function Worker_fn() {
18 | return new Worker(__webpack_public_path__ + \\"test.worker.js\\");
19 | }
20 | "
21 | `;
22 |
23 | exports[`"esModule" option should work with "false" value: result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
24 |
25 | exports[`"esModule" option should work with "false" value: warnings 1`] = `Array []`;
26 |
27 | exports[`"esModule" option should work with "true" value: errors 1`] = `Array []`;
28 |
29 | exports[`"esModule" option should work with "true" value: module 1`] = `
30 | "export default function Worker_fn() {
31 | return new Worker(__webpack_public_path__ + \\"test.worker.js\\");
32 | }
33 | "
34 | `;
35 |
36 | exports[`"esModule" option should work with "true" value: result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
37 |
38 | exports[`"esModule" option should work with "true" value: warnings 1`] = `Array []`;
39 |
--------------------------------------------------------------------------------
/test/__snapshots__/filename-options.test.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`"filename" option should work ("function"): errors 1`] = `Array []`;
4 |
5 | exports[`"filename" option should work ("function"): module 1`] = `
6 | "export default function Worker_fn() {
7 | return new Worker(__webpack_public_path__ + \\"worker.custom.worker.js\\");
8 | }
9 | "
10 | `;
11 |
12 | exports[`"filename" option should work ("function"): result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
13 |
14 | exports[`"filename" option should work ("function"): warnings 1`] = `Array []`;
15 |
16 | exports[`"filename" option should work ("string"): errors 1`] = `Array []`;
17 |
18 | exports[`"filename" option should work ("string"): module 1`] = `
19 | "export default function Worker_fn() {
20 | return new Worker(__webpack_public_path__ + \\"worker.custom.worker.js\\");
21 | }
22 | "
23 | `;
24 |
25 | exports[`"filename" option should work ("string"): result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
26 |
27 | exports[`"filename" option should work ("string"): warnings 1`] = `Array []`;
28 |
29 | exports[`"filename" option should work and respect the "output.filename" default value option: errors 1`] = `Array []`;
30 |
31 | exports[`"filename" option should work and respect the "output.filename" default value option: module 1`] = `
32 | "export default function Worker_fn() {
33 | return new Worker(__webpack_public_path__ + \\"worker.worker.js\\");
34 | }
35 | "
36 | `;
37 |
38 | exports[`"filename" option should work and respect the "output.filename" default value option: result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
39 |
40 | exports[`"filename" option should work and respect the "output.filename" default value option: warnings 1`] = `Array []`;
41 |
42 | exports[`"filename" option should work and respect the "output.filename" option ("function"): errors 1`] = `Array []`;
43 |
44 | exports[`"filename" option should work and respect the "output.filename" option ("function"): module 1`] = `
45 | "export default function Worker_fn() {
46 | return new Worker(__webpack_public_path__ + \\"worker.custom.worker.js\\");
47 | }
48 | "
49 | `;
50 |
51 | exports[`"filename" option should work and respect the "output.filename" option ("function"): result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
52 |
53 | exports[`"filename" option should work and respect the "output.filename" option ("function"): warnings 1`] = `Array []`;
54 |
55 | exports[`"filename" option should work and respect the "output.filename" option ("string"): errors 1`] = `Array []`;
56 |
57 | exports[`"filename" option should work and respect the "output.filename" option ("string"): module 1`] = `
58 | "export default function Worker_fn() {
59 | return new Worker(__webpack_public_path__ + \\"worker.custom.worker.js\\");
60 | }
61 | "
62 | `;
63 |
64 | exports[`"filename" option should work and respect the "output.filename" option ("string"): result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
65 |
66 | exports[`"filename" option should work and respect the "output.filename" option ("string"): warnings 1`] = `Array []`;
67 |
--------------------------------------------------------------------------------
/test/__snapshots__/inline-option.test.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`"inline" option should not work by default: errors 1`] = `Array []`;
4 |
5 | exports[`"inline" option should not work by default: module 1`] = `
6 | "export default function Worker_fn() {
7 | return new Worker(__webpack_public_path__ + \\"test.worker.js\\");
8 | }
9 | "
10 | `;
11 |
12 | exports[`"inline" option should not work by default: result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
13 |
14 | exports[`"inline" option should not work by default: warnings 1`] = `Array []`;
15 |
16 | exports[`"inline" option should work with "fallback" value and "esModule" with "false" value: errors 1`] = `Array []`;
17 |
18 | exports[`"inline" option should work with "fallback" value and "esModule" with "false" value: result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
19 |
20 | exports[`"inline" option should work with "fallback" value and "esModule" with "false" value: warnings 1`] = `Array []`;
21 |
22 | exports[`"inline" option should work with "fallback" value and "esModule" with "true" value: errors 1`] = `Array []`;
23 |
24 | exports[`"inline" option should work with "fallback" value and "esModule" with "true" value: result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
25 |
26 | exports[`"inline" option should work with "fallback" value and "esModule" with "true" value: warnings 1`] = `Array []`;
27 |
28 | exports[`"inline" option should work with "fallback" value and the "devtool" option ("source-map" value): errors 1`] = `Array []`;
29 |
30 | exports[`"inline" option should work with "fallback" value and the "devtool" option ("source-map" value): errors 2`] = `Array []`;
31 |
32 | exports[`"inline" option should work with "fallback" value and the "devtool" option ("source-map" value): result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
33 |
34 | exports[`"inline" option should work with "fallback" value and the "devtool" option ("source-map" value): result 2`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
35 |
36 | exports[`"inline" option should work with "fallback" value and the "devtool" option ("source-map" value): warnings 1`] = `Array []`;
37 |
38 | exports[`"inline" option should work with "fallback" value and the "devtool" option ("source-map" value): warnings 2`] = `Array []`;
39 |
40 | exports[`"inline" option should work with "fallback" value: errors 1`] = `Array []`;
41 |
42 | exports[`"inline" option should work with "fallback" value: result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
43 |
44 | exports[`"inline" option should work with "fallback" value: warnings 1`] = `Array []`;
45 |
46 | exports[`"inline" option should work with "no-fallback" value and "esModule" with "false" value: errors 1`] = `Array []`;
47 |
48 | exports[`"inline" option should work with "no-fallback" value and "esModule" with "false" value: result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
49 |
50 | exports[`"inline" option should work with "no-fallback" value and "esModule" with "false" value: warnings 1`] = `Array []`;
51 |
52 | exports[`"inline" option should work with "no-fallback" value and "esModule" with "true" value: errors 1`] = `Array []`;
53 |
54 | exports[`"inline" option should work with "no-fallback" value and "esModule" with "true" value: result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
55 |
56 | exports[`"inline" option should work with "no-fallback" value and "esModule" with "true" value: warnings 1`] = `Array []`;
57 |
58 | exports[`"inline" option should work with "no-fallback" value and the "devtool" option ("eval-source-map" value): errors 1`] = `Array []`;
59 |
60 | exports[`"inline" option should work with "no-fallback" value and the "devtool" option ("eval-source-map" value): result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
61 |
62 | exports[`"inline" option should work with "no-fallback" value and the "devtool" option ("eval-source-map" value): warnings 1`] = `Array []`;
63 |
64 | exports[`"inline" option should work with "no-fallback" value and the "devtool" option ("source-map" value): errors 1`] = `Array []`;
65 |
66 | exports[`"inline" option should work with "no-fallback" value and the "devtool" option ("source-map" value): errors 2`] = `Array []`;
67 |
68 | exports[`"inline" option should work with "no-fallback" value and the "devtool" option ("source-map" value): result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
69 |
70 | exports[`"inline" option should work with "no-fallback" value and the "devtool" option ("source-map" value): result 2`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
71 |
72 | exports[`"inline" option should work with "no-fallback" value and the "devtool" option ("source-map" value): warnings 1`] = `Array []`;
73 |
74 | exports[`"inline" option should work with "no-fallback" value and the "devtool" option ("source-map" value): warnings 2`] = `Array []`;
75 |
76 | exports[`"inline" option should work with "no-fallback" value: errors 1`] = `Array []`;
77 |
78 | exports[`"inline" option should work with "no-fallback" value: result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
79 |
80 | exports[`"inline" option should work with "no-fallback" value: warnings 1`] = `Array []`;
81 |
--------------------------------------------------------------------------------
/test/__snapshots__/loader.test.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`worker-loader should work and have the same base file name as the source files: errors 1`] = `Array []`;
4 |
5 | exports[`worker-loader should work and have the same base file name as the source files: module 1`] = `
6 | "export default function Worker_fn() {
7 | return new Worker(__webpack_public_path__ + \\"TypeDetection.worker.js\\");
8 | }
9 | "
10 | `;
11 |
12 | exports[`worker-loader should work and have the same base file name as the source files: result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
13 |
14 | exports[`worker-loader should work and have the same base file name as the source files: warnings 1`] = `Array []`;
15 |
16 | exports[`worker-loader should work and respect the "devtool" option ("false" value): errors 1`] = `Array []`;
17 |
18 | exports[`worker-loader should work and respect the "devtool" option ("false" value): module 1`] = `
19 | "export default function Worker_fn() {
20 | return new Worker(__webpack_public_path__ + \\"test.worker.js\\");
21 | }
22 | "
23 | `;
24 |
25 | exports[`worker-loader should work and respect the "devtool" option ("false" value): result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
26 |
27 | exports[`worker-loader should work and respect the "devtool" option ("false" value): warnings 1`] = `Array []`;
28 |
29 | exports[`worker-loader should work and respect the "devtool" option ("source-map" value): errors 1`] = `Array []`;
30 |
31 | exports[`worker-loader should work and respect the "devtool" option ("source-map" value): module 1`] = `
32 | "export default function Worker_fn() {
33 | return new Worker(__webpack_public_path__ + \\"test.worker.js\\");
34 | }
35 | "
36 | `;
37 |
38 | exports[`worker-loader should work and respect the "devtool" option ("source-map" value): result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
39 |
40 | exports[`worker-loader should work and respect the "devtool" option ("source-map" value): warnings 1`] = `Array []`;
41 |
42 | exports[`worker-loader should work with "externals": errors 1`] = `Array []`;
43 |
44 | exports[`worker-loader should work with "externals": module 1`] = `
45 | "export default function Worker_fn() {
46 | return new Worker(__webpack_public_path__ + \\"test.worker.js\\");
47 | }
48 | "
49 | `;
50 |
51 | exports[`worker-loader should work with "externals": result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
52 |
53 | exports[`worker-loader should work with "externals": warnings 1`] = `Array []`;
54 |
55 | exports[`worker-loader should work with WASM: errors 1`] = `Array []`;
56 |
57 | exports[`worker-loader should work with WASM: module 1`] = `
58 | "export default function Worker_fn() {
59 | return new Worker(__webpack_public_path__ + \\"test.worker.js\\");
60 | }
61 | "
62 | `;
63 |
64 | exports[`worker-loader should work with WASM: result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":30}"`;
65 |
66 | exports[`worker-loader should work with WASM: warnings 1`] = `Array []`;
67 |
68 | exports[`worker-loader should work with async chunks: errors 1`] = `Array []`;
69 |
70 | exports[`worker-loader should work with async chunks: module 1`] = `
71 | "export default function Worker_fn() {
72 | return new Worker(__webpack_public_path__ + \\"test.worker.js\\");
73 | }
74 | "
75 | `;
76 |
77 | exports[`worker-loader should work with async chunks: result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
78 |
79 | exports[`worker-loader should work with async chunks: warnings 1`] = `Array []`;
80 |
81 | exports[`worker-loader should work with inline syntax: errors 1`] = `Array []`;
82 |
83 | exports[`worker-loader should work with inline syntax: module 1`] = `
84 | "export default function Worker_fn() {
85 | return new Worker(__webpack_public_path__ + \\"test.worker.js\\");
86 | }
87 | "
88 | `;
89 |
90 | exports[`worker-loader should work with inline syntax: result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
91 |
92 | exports[`worker-loader should work with inline syntax: warnings 1`] = `Array []`;
93 |
94 | exports[`worker-loader should work: errors 1`] = `Array []`;
95 |
96 | exports[`worker-loader should work: module 1`] = `
97 | "export default function Worker_fn() {
98 | return new Worker(__webpack_public_path__ + \\"test.worker.js\\");
99 | }
100 | "
101 | `;
102 |
103 | exports[`worker-loader should work: result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
104 |
105 | exports[`worker-loader should work: warnings 1`] = `Array []`;
106 |
--------------------------------------------------------------------------------
/test/__snapshots__/publicPath.test.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`"publicPath" option should work and respect "filename" and "chunkFilename" option values: errors 1`] = `Array []`;
4 |
5 | exports[`"publicPath" option should work and respect "filename" and "chunkFilename" option values: errors 2`] = `Array []`;
6 |
7 | exports[`"publicPath" option should work and respect "filename" and "chunkFilename" option values: module 1`] = `
8 | "export default function Worker_fn() {
9 | return new Worker(__webpack_public_path__ + \\"other-static/js/worker.bundle.worker.js\\");
10 | }
11 | "
12 | `;
13 |
14 | exports[`"publicPath" option should work and respect "filename" and "chunkFilename" option values: module 2`] = `
15 | "export default function Worker_fn() {
16 | return new Worker(__webpack_public_path__ + \\"other-static/js/worker.worker.js\\");
17 | }
18 | "
19 | `;
20 |
21 | exports[`"publicPath" option should work and respect "filename" and "chunkFilename" option values: result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
22 |
23 | exports[`"publicPath" option should work and respect "filename" and "chunkFilename" option values: result 2`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
24 |
25 | exports[`"publicPath" option should work and respect "filename" and "chunkFilename" option values: warnings 1`] = `Array []`;
26 |
27 | exports[`"publicPath" option should work and respect "filename" and "chunkFilename" option values: warnings 2`] = `Array []`;
28 |
29 | exports[`"publicPath" option should work and respect the "output.publicPath" option default value: errors 1`] = `Array []`;
30 |
31 | exports[`"publicPath" option should work and respect the "output.publicPath" option default value: module 1`] = `
32 | "export default function Worker_fn() {
33 | return new Worker(__webpack_public_path__ + \\"test.worker.js\\");
34 | }
35 | "
36 | `;
37 |
38 | exports[`"publicPath" option should work and respect the "output.publicPath" option default value: result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
39 |
40 | exports[`"publicPath" option should work and respect the "output.publicPath" option default value: warnings 1`] = `Array []`;
41 |
42 | exports[`"publicPath" option should work and respect the "output.publicPath" option value ("function"): errors 1`] = `Array []`;
43 |
44 | exports[`"publicPath" option should work and respect the "output.publicPath" option value ("function"): module 1`] = `
45 | "export default function Worker_fn() {
46 | return new Worker(__webpack_public_path__ + \\"test.worker.js\\");
47 | }
48 | "
49 | `;
50 |
51 | exports[`"publicPath" option should work and respect the "output.publicPath" option value ("function"): result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
52 |
53 | exports[`"publicPath" option should work and respect the "output.publicPath" option value ("function"): warnings 1`] = `Array []`;
54 |
55 | exports[`"publicPath" option should work and respect the "output.publicPath" option value ("string"): errors 1`] = `Array []`;
56 |
57 | exports[`"publicPath" option should work and respect the "output.publicPath" option value ("string"): module 1`] = `
58 | "export default function Worker_fn() {
59 | return new Worker(__webpack_public_path__ + \\"test.worker.js\\");
60 | }
61 | "
62 | `;
63 |
64 | exports[`"publicPath" option should work and respect the "output.publicPath" option value ("string"): result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
65 |
66 | exports[`"publicPath" option should work and respect the "output.publicPath" option value ("string"): warnings 1`] = `Array []`;
67 |
68 | exports[`"publicPath" option should work and respect the "publicPath" option ("function"): errors 1`] = `Array []`;
69 |
70 | exports[`"publicPath" option should work and respect the "publicPath" option ("function"): module 1`] = `
71 | "export default function Worker_fn() {
72 | return new Worker(__webpack_public_path__ + \\"test.worker.js\\");
73 | }
74 | "
75 | `;
76 |
77 | exports[`"publicPath" option should work and respect the "publicPath" option ("function"): result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
78 |
79 | exports[`"publicPath" option should work and respect the "publicPath" option ("function"): warnings 1`] = `Array []`;
80 |
81 | exports[`"publicPath" option should work and respect the "publicPath" option ("string"): errors 1`] = `Array []`;
82 |
83 | exports[`"publicPath" option should work and respect the "publicPath" option ("string"): module 1`] = `
84 | "export default function Worker_fn() {
85 | return new Worker(__webpack_public_path__ + \\"test.worker.js\\");
86 | }
87 | "
88 | `;
89 |
90 | exports[`"publicPath" option should work and respect the "publicPath" option ("string"): result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
91 |
92 | exports[`"publicPath" option should work and respect the "publicPath" option ("string"): warnings 1`] = `Array []`;
93 |
94 | exports[`"publicPath" option should work and use "__webpack_public_path__" by default: errors 1`] = `Array []`;
95 |
96 | exports[`"publicPath" option should work and use "__webpack_public_path__" by default: module 1`] = `
97 | "export default function Worker_fn() {
98 | return new Worker(__webpack_public_path__ + \\"test.worker.js\\");
99 | }
100 | "
101 | `;
102 |
103 | exports[`"publicPath" option should work and use "__webpack_public_path__" by default: result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
104 |
105 | exports[`"publicPath" option should work and use "__webpack_public_path__" by default: warnings 1`] = `Array []`;
106 |
--------------------------------------------------------------------------------
/test/__snapshots__/sourceMapperRegexp.test.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`source-map-loader should work with "
4 | with SourceMap
5 |
6 | // #sourceMappingURL = /sample-source-map.map
7 | // comment
8 | " url: result 1`] = `
9 | "
10 | with SourceMap
11 |
12 | REPLASED// comment
13 | "
14 | `;
15 |
16 | exports[`source-map-loader should work with " // # sourceMappingURL = absolute-sourceRoot-source-map.map " url: result 1`] = `" REPLASED"`;
17 |
18 | exports[`source-map-loader should work with " // #sourceMappingURL=absolute-sourceRoot-source-map.map" url: result 1`] = `" REPLASED"`;
19 |
20 | exports[`source-map-loader should work with "/* #sourceMappingURL=absolute-sourceRoot-source-map.map */" url: result 1`] = `"REPLASED"`;
21 |
22 | exports[`source-map-loader should work with "/*#sourceMappingURL=absolute-sourceRoot-source-map.map*/" url: result 1`] = `"REPLASED"`;
23 |
24 | exports[`source-map-loader should work with "// #sourceMappingURL = //sampledomain.com/external-source-map2.map" url: result 1`] = `"REPLASED"`;
25 |
26 | exports[`source-map-loader should work with "// #sourceMappingURL = http://sampledomain.com/external-source-map2.map" url: result 1`] = `"REPLASED"`;
27 |
28 | exports[`source-map-loader should work with "// @sourceMappingURL=data:application/source-map;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5saW5lLXNvdXJjZS1tYXAuanMiLCJzb3VyY2VzIjpbImlubGluZS1zb3VyY2UtbWFwLnR4dCJdLCJzb3VyY2VzQ29udGVudCI6WyJ3aXRoIFNvdXJjZU1hcCJdLCJtYXBwaW5ncyI6IkFBQUEifQ==" url: result 1`] = `"REPLASED"`;
29 |
30 | exports[`source-map-loader should work with "//#sourceMappingURL=absolute-sourceRoot-source-map.map" url: result 1`] = `"REPLASED"`;
31 |
32 | exports[`source-map-loader should work with "//@sourceMappingURL=absolute-sourceRoot-source-map.map" url: result 1`] = `"REPLASED"`;
33 |
34 | exports[`source-map-loader should work with "onmessage = function(event) {
35 | const workerResult = event.data;
36 |
37 | workerResult.onmessage = true;
38 |
39 | postMessage(workerResult);
40 | };
41 | //# sourceURL=[module]
42 | //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9iYXNpYy93b3JrZXIuanM/OGFiZiJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTtBQUNBOztBQUVBOztBQUVBO0FBQ0EiLCJmaWxlIjoiLi9iYXNpYy93b3JrZXIuanMuanMiLCJzb3VyY2VzQ29udGVudCI6WyJvbm1lc3NhZ2UgPSBmdW5jdGlvbihldmVudCkge1xuICBjb25zdCB3b3JrZXJSZXN1bHQgPSBldmVudC5kYXRhO1xuXG4gIHdvcmtlclJlc3VsdC5vbm1lc3NhZ2UgPSB0cnVlO1xuXG4gIHBvc3RNZXNzYWdlKHdvcmtlclJlc3VsdCk7XG59O1xuIl0sInNvdXJjZVJvb3QiOiIifQ==
43 | //# sourceURL=webpack-internal:///./basic/worker.js
44 | " url: result 1`] = `
45 | "onmessage = function(event) {
46 | const workerResult = event.data;
47 |
48 | workerResult.onmessage = true;
49 |
50 | postMessage(workerResult);
51 | };
52 | //# sourceURL=[module]
53 | REPLASED//# sourceURL=webpack-internal:///./basic/worker.js
54 | "
55 | `;
56 |
--------------------------------------------------------------------------------
/test/__snapshots__/validate-options.test.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`validate options should throw an error on the "chunkFilename" option with "[]" value 1`] = `
4 | "Invalid options object. Worker Loader has been initialized using an options object that does not match the API schema.
5 | - options.chunkFilename should be a non-empty string.
6 | -> The filename of non-entry chunks for web workers.
7 | -> Read more at https://github.com/webpack-contrib/worker-loader#chunkfilename"
8 | `;
9 |
10 | exports[`validate options should throw an error on the "chunkFilename" option with "true" value 1`] = `
11 | "Invalid options object. Worker Loader has been initialized using an options object that does not match the API schema.
12 | - options.chunkFilename should be a non-empty string.
13 | -> The filename of non-entry chunks for web workers.
14 | -> Read more at https://github.com/webpack-contrib/worker-loader#chunkfilename"
15 | `;
16 |
17 | exports[`validate options should throw an error on the "esModule" option with "true" value 1`] = `
18 | "Invalid options object. Worker Loader has been initialized using an options object that does not match the API schema.
19 | - options.esModule should be a boolean.
20 | -> Enable or disable ES module syntax.
21 | -> Read more at https://github.com/webpack-contrib/worker-loader#esmodule"
22 | `;
23 |
24 | exports[`validate options should throw an error on the "filename" option with "[]" value 1`] = `
25 | "Invalid options object. Worker Loader has been initialized using an options object that does not match the API schema.
26 | - options.filename should be one of these:
27 | non-empty string | function
28 | -> The filename of entry chunks for web workers.
29 | -> Read more at https://github.com/webpack-contrib/worker-loader#filename
30 | Details:
31 | * options.filename should be a non-empty string.
32 | * options.filename should be an instance of function."
33 | `;
34 |
35 | exports[`validate options should throw an error on the "filename" option with "true" value 1`] = `
36 | "Invalid options object. Worker Loader has been initialized using an options object that does not match the API schema.
37 | - options.filename should be one of these:
38 | non-empty string | function
39 | -> The filename of entry chunks for web workers.
40 | -> Read more at https://github.com/webpack-contrib/worker-loader#filename
41 | Details:
42 | * options.filename should be a non-empty string.
43 | * options.filename should be an instance of function."
44 | `;
45 |
46 | exports[`validate options should throw an error on the "inline" option with "true" value 1`] = `
47 | "Invalid options object. Worker Loader has been initialized using an options object that does not match the API schema.
48 | - options.inline should be one of these:
49 | \\"no-fallback\\" | \\"fallback\\"
50 | -> Allow to inline the worker as a BLOB.
51 | -> Read more at https://github.com/webpack-contrib/worker-loader#inline"
52 | `;
53 |
54 | exports[`validate options should throw an error on the "inline" option with "true" value 2`] = `
55 | "Invalid options object. Worker Loader has been initialized using an options object that does not match the API schema.
56 | - options.inline should be one of these:
57 | \\"no-fallback\\" | \\"fallback\\"
58 | -> Allow to inline the worker as a BLOB.
59 | -> Read more at https://github.com/webpack-contrib/worker-loader#inline"
60 | `;
61 |
62 | exports[`validate options should throw an error on the "publicPath" option with "[]" value 1`] = `
63 | "Invalid options object. Worker Loader has been initialized using an options object that does not match the API schema.
64 | - options.publicPath should be one of these:
65 | string | function
66 | -> Specifies the public URL address of the output files when referenced in a browser.
67 | -> Read more at https://github.com/webpack-contrib/worker-loader#publicpath
68 | Details:
69 | * options.publicPath should be a string.
70 | * options.publicPath should be an instance of function."
71 | `;
72 |
73 | exports[`validate options should throw an error on the "publicPath" option with "true" value 1`] = `
74 | "Invalid options object. Worker Loader has been initialized using an options object that does not match the API schema.
75 | - options.publicPath should be one of these:
76 | string | function
77 | -> Specifies the public URL address of the output files when referenced in a browser.
78 | -> Read more at https://github.com/webpack-contrib/worker-loader#publicpath
79 | Details:
80 | * options.publicPath should be a string.
81 | * options.publicPath should be an instance of function."
82 | `;
83 |
84 | exports[`validate options should throw an error on the "unknown" option with "/test/" value 1`] = `
85 | "Invalid options object. Worker Loader has been initialized using an options object that does not match the API schema.
86 | - options has an unknown property 'unknown'. These properties are valid:
87 | object { worker?, publicPath?, filename?, chunkFilename?, inline?, esModule? }"
88 | `;
89 |
90 | exports[`validate options should throw an error on the "unknown" option with "[]" value 1`] = `
91 | "Invalid options object. Worker Loader has been initialized using an options object that does not match the API schema.
92 | - options has an unknown property 'unknown'. These properties are valid:
93 | object { worker?, publicPath?, filename?, chunkFilename?, inline?, esModule? }"
94 | `;
95 |
96 | exports[`validate options should throw an error on the "unknown" option with "{"foo":"bar"}" value 1`] = `
97 | "Invalid options object. Worker Loader has been initialized using an options object that does not match the API schema.
98 | - options has an unknown property 'unknown'. These properties are valid:
99 | object { worker?, publicPath?, filename?, chunkFilename?, inline?, esModule? }"
100 | `;
101 |
102 | exports[`validate options should throw an error on the "unknown" option with "{}" value 1`] = `
103 | "Invalid options object. Worker Loader has been initialized using an options object that does not match the API schema.
104 | - options has an unknown property 'unknown'. These properties are valid:
105 | object { worker?, publicPath?, filename?, chunkFilename?, inline?, esModule? }"
106 | `;
107 |
108 | exports[`validate options should throw an error on the "unknown" option with "1" value 1`] = `
109 | "Invalid options object. Worker Loader has been initialized using an options object that does not match the API schema.
110 | - options has an unknown property 'unknown'. These properties are valid:
111 | object { worker?, publicPath?, filename?, chunkFilename?, inline?, esModule? }"
112 | `;
113 |
114 | exports[`validate options should throw an error on the "unknown" option with "false" value 1`] = `
115 | "Invalid options object. Worker Loader has been initialized using an options object that does not match the API schema.
116 | - options has an unknown property 'unknown'. These properties are valid:
117 | object { worker?, publicPath?, filename?, chunkFilename?, inline?, esModule? }"
118 | `;
119 |
120 | exports[`validate options should throw an error on the "unknown" option with "test" value 1`] = `
121 | "Invalid options object. Worker Loader has been initialized using an options object that does not match the API schema.
122 | - options has an unknown property 'unknown'. These properties are valid:
123 | object { worker?, publicPath?, filename?, chunkFilename?, inline?, esModule? }"
124 | `;
125 |
126 | exports[`validate options should throw an error on the "unknown" option with "true" value 1`] = `
127 | "Invalid options object. Worker Loader has been initialized using an options object that does not match the API schema.
128 | - options has an unknown property 'unknown'. These properties are valid:
129 | object { worker?, publicPath?, filename?, chunkFilename?, inline?, esModule? }"
130 | `;
131 |
132 | exports[`validate options should throw an error on the "worker" option with "[]" value 1`] = `
133 | "Invalid options object. Worker Loader has been initialized using an options object that does not match the API schema.
134 | - options.worker should be one of these:
135 | non-empty string | object { type, options? }
136 | -> Set the worker type.
137 | -> Read more at https://github.com/webpack-contrib/worker-loader#worker
138 | Details:
139 | * options.worker should be a non-empty string.
140 | * options.worker should be an object:
141 | object { type, options? }"
142 | `;
143 |
144 | exports[`validate options should throw an error on the "worker" option with "true" value 1`] = `
145 | "Invalid options object. Worker Loader has been initialized using an options object that does not match the API schema.
146 | - options.worker should be one of these:
147 | non-empty string | object { type, options? }
148 | -> Set the worker type.
149 | -> Read more at https://github.com/webpack-contrib/worker-loader#worker
150 | Details:
151 | * options.worker should be a non-empty string.
152 | * options.worker should be an object:
153 | object { type, options? }"
154 | `;
155 |
--------------------------------------------------------------------------------
/test/__snapshots__/worker-option.test.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`"workerType" option should support the "Worker" object value for inline workers with fallback: errors 1`] = `Array []`;
4 |
5 | exports[`"workerType" option should support the "Worker" object value for inline workers with fallback: result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
6 |
7 | exports[`"workerType" option should support the "Worker" object value for inline workers with fallback: warnings 1`] = `Array []`;
8 |
9 | exports[`"workerType" option should support the "Worker" object value for inline workers without fallback: errors 1`] = `Array []`;
10 |
11 | exports[`"workerType" option should support the "Worker" object value for inline workers without fallback: result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
12 |
13 | exports[`"workerType" option should support the "Worker" object value for inline workers without fallback: warnings 1`] = `Array []`;
14 |
15 | exports[`"workerType" option should support the "Worker" object value: errors 1`] = `Array []`;
16 |
17 | exports[`"workerType" option should support the "Worker" object value: module 1`] = `
18 | "export default function Worker_fn() {
19 | return new Worker(__webpack_public_path__ + \\"test.worker.js\\", {\\"type\\":\\"classic\\",\\"name\\":\\"worker-name\\"});
20 | }
21 | "
22 | `;
23 |
24 | exports[`"workerType" option should support the "Worker" object value: result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
25 |
26 | exports[`"workerType" option should support the "Worker" object value: warnings 1`] = `Array []`;
27 |
28 | exports[`"workerType" option should support the "Worker" string value: errors 1`] = `Array []`;
29 |
30 | exports[`"workerType" option should support the "Worker" string value: module 1`] = `
31 | "export default function Worker_fn() {
32 | return new Worker(__webpack_public_path__ + \\"test.worker.js\\");
33 | }
34 | "
35 | `;
36 |
37 | exports[`"workerType" option should support the "Worker" string value: result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
38 |
39 | exports[`"workerType" option should support the "Worker" string value: warnings 1`] = `Array []`;
40 |
41 | exports[`"workerType" option should use "Worker" by default: errors 1`] = `Array []`;
42 |
43 | exports[`"workerType" option should use "Worker" by default: module 1`] = `
44 | "export default function Worker_fn() {
45 | return new Worker(__webpack_public_path__ + \\"test.worker.js\\");
46 | }
47 | "
48 | `;
49 |
50 | exports[`"workerType" option should use "Worker" by default: result 1`] = `"{\\"postMessage\\":true,\\"onmessage\\":true}"`;
51 |
52 | exports[`"workerType" option should use "Worker" by default: warnings 1`] = `Array []`;
53 |
--------------------------------------------------------------------------------
/test/chunkFilename-option.test.js:
--------------------------------------------------------------------------------
1 | import path from "path";
2 |
3 | import { customAlphabet } from "nanoid";
4 |
5 | import {
6 | compile,
7 | getCompiler,
8 | getErrors,
9 | getModuleSource,
10 | getResultFromBrowser,
11 | getWarnings,
12 | } from "./helpers";
13 |
14 | describe('"name" option', () => {
15 | it('should work ("string")', async () => {
16 | const compiler = getCompiler("./chunks/entry.js", {
17 | chunkFilename: "test.worker.chunk.js",
18 | });
19 | const stats = await compile(compiler);
20 | const result = await getResultFromBrowser(stats);
21 |
22 | expect(getModuleSource("./chunks/worker.js", stats)).toMatchSnapshot(
23 | "module"
24 | );
25 | expect(result).toMatchSnapshot("result");
26 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
27 | expect(getErrors(stats)).toMatchSnapshot("errors");
28 | });
29 |
30 | it('should work and respect the "output.chunkFilename" default value option', async () => {
31 | const nanoid = customAlphabet("1234567890abcdef", 10);
32 | const compiler = getCompiler(
33 | "./chunks/entry.js",
34 | {},
35 | {
36 | output: {
37 | path: path.resolve(__dirname, "./outputs", `test_${nanoid()}`),
38 | filename: "[name].js",
39 | publicPath: "",
40 | },
41 | module: {
42 | rules: [
43 | {
44 | test: /worker\.js$/i,
45 | rules: [
46 | {
47 | loader: path.resolve(__dirname, "../src"),
48 | },
49 | ],
50 | },
51 | ],
52 | },
53 | }
54 | );
55 | const stats = await compile(compiler);
56 | const result = await getResultFromBrowser(stats);
57 |
58 | expect(getModuleSource("./chunks/worker.js", stats)).toMatchSnapshot(
59 | "module"
60 | );
61 | expect(result).toMatchSnapshot("result");
62 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
63 | expect(getErrors(stats)).toMatchSnapshot("errors");
64 | });
65 |
66 | it('should work and respect the "output.chunkFilename" option ("string")', async () => {
67 | const nanoid = customAlphabet("1234567890abcdef", 10);
68 | const compiler = getCompiler(
69 | "./chunks/entry.js",
70 | {},
71 | {
72 | output: {
73 | path: path.resolve(__dirname, "./outputs", `test_${nanoid()}`),
74 | filename: "[name].js",
75 | chunkFilename: "[name].chunk.js",
76 | publicPath: "",
77 | },
78 | module: {
79 | rules: [
80 | {
81 | test: /worker\.js$/i,
82 | rules: [
83 | {
84 | loader: path.resolve(__dirname, "../src"),
85 | },
86 | ],
87 | },
88 | ],
89 | },
90 | }
91 | );
92 | const stats = await compile(compiler);
93 | const result = await getResultFromBrowser(stats);
94 |
95 | expect(getModuleSource("./chunks/worker.js", stats)).toMatchSnapshot(
96 | "module"
97 | );
98 | expect(result).toMatchSnapshot("result");
99 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
100 | expect(getErrors(stats)).toMatchSnapshot("errors");
101 | });
102 |
103 | it("should chunkFilename suffix be inserted before query parameters", async () => {
104 | const nanoid = customAlphabet("1234567890abcdef", 10);
105 | const compiler = getCompiler(
106 | "./chunks/entry.js",
107 | {},
108 | {
109 | output: {
110 | path: path.resolve(__dirname, "./outputs", `test_${nanoid()}`),
111 | filename: "[name].js",
112 | chunkFilename: "[name].chunk.js?foo=bar&baz=bar",
113 | publicPath: "",
114 | },
115 | module: {
116 | rules: [
117 | {
118 | test: /worker\.js$/i,
119 | rules: [
120 | {
121 | loader: path.resolve(__dirname, "../src"),
122 | },
123 | ],
124 | },
125 | ],
126 | },
127 | }
128 | );
129 | const stats = await compile(compiler);
130 | const result = await getResultFromBrowser(stats);
131 |
132 | let hasChankName = false;
133 |
134 | Object.keys(stats.compilation.assets).forEach((asset) => {
135 | if (asset.endsWith("chunk.worker.js?foo=bar&baz=bar")) {
136 | hasChankName = true;
137 | }
138 | });
139 |
140 | expect(hasChankName).toBe(true);
141 | expect(result).toMatchSnapshot("result");
142 | expect(getModuleSource("./chunks/worker.js", stats)).toMatchSnapshot(
143 | "module"
144 | );
145 | expect(result).toMatchSnapshot("result");
146 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
147 | expect(getErrors(stats)).toMatchSnapshot("errors");
148 | });
149 | });
150 |
--------------------------------------------------------------------------------
/test/cjs.test.js:
--------------------------------------------------------------------------------
1 | import src from "../src";
2 | import cjs from "../src/cjs";
3 |
4 | describe("cjs", () => {
5 | it("should exported", () => {
6 | expect(cjs).toEqual(src);
7 | });
8 | });
9 |
--------------------------------------------------------------------------------
/test/esModule-option.test.js:
--------------------------------------------------------------------------------
1 | import {
2 | compile,
3 | getCompiler,
4 | getErrors,
5 | getModuleSource,
6 | getResultFromBrowser,
7 | getWarnings,
8 | } from "./helpers";
9 |
10 | describe('"esModule" option', () => {
11 | it("should work and generate ES module syntax by default", async () => {
12 | const compiler = getCompiler("./basic/entry.js");
13 | const stats = await compile(compiler);
14 | // const result = await getResultFromBrowser(stats);
15 |
16 | expect(getModuleSource("./basic/worker.js", stats)).toMatchSnapshot(
17 | "module"
18 | );
19 | // expect(result).toMatchSnapshot('result');
20 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
21 | expect(getErrors(stats)).toMatchSnapshot("errors");
22 | });
23 |
24 | it('should work with "true" value', async () => {
25 | const compiler = getCompiler("./basic/entry.js", {
26 | esModule: true,
27 | });
28 | const stats = await compile(compiler);
29 | const result = await getResultFromBrowser(stats);
30 |
31 | expect(getModuleSource("./basic/worker.js", stats)).toMatchSnapshot(
32 | "module"
33 | );
34 | expect(result).toMatchSnapshot("result");
35 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
36 | expect(getErrors(stats)).toMatchSnapshot("errors");
37 | });
38 |
39 | it('should work with "false" value', async () => {
40 | const compiler = getCompiler("./basic/entry.js", {
41 | esModule: false,
42 | });
43 | const stats = await compile(compiler);
44 | const result = await getResultFromBrowser(stats);
45 |
46 | expect(getModuleSource("./basic/worker.js", stats)).toMatchSnapshot(
47 | "module"
48 | );
49 | expect(result).toMatchSnapshot("result");
50 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
51 | expect(getErrors(stats)).toMatchSnapshot("errors");
52 | });
53 | });
54 |
--------------------------------------------------------------------------------
/test/filename-options.test.js:
--------------------------------------------------------------------------------
1 | import path from "path";
2 |
3 | import { customAlphabet } from "nanoid";
4 |
5 | import {
6 | compile,
7 | getCompiler,
8 | getErrors,
9 | getModuleSource,
10 | getResultFromBrowser,
11 | getWarnings,
12 | } from "./helpers";
13 |
14 | describe('"filename" option', () => {
15 | it('should work ("string")', async () => {
16 | const compiler = getCompiler("./chunks/entry.js", {
17 | filename: "[name].custom.worker.js",
18 | });
19 | const stats = await compile(compiler);
20 | const result = await getResultFromBrowser(stats);
21 |
22 | expect(getModuleSource("./chunks/worker.js", stats)).toMatchSnapshot(
23 | "module"
24 | );
25 | expect(result).toMatchSnapshot("result");
26 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
27 | expect(getErrors(stats)).toMatchSnapshot("errors");
28 | });
29 |
30 | it('should work ("function")', async () => {
31 | const compiler = getCompiler("./chunks/entry.js", {
32 | filename: () => "[name].custom.worker.js",
33 | });
34 | const stats = await compile(compiler);
35 | const result = await getResultFromBrowser(stats);
36 |
37 | expect(getModuleSource("./chunks/worker.js", stats)).toMatchSnapshot(
38 | "module"
39 | );
40 | expect(result).toMatchSnapshot("result");
41 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
42 | expect(getErrors(stats)).toMatchSnapshot("errors");
43 | });
44 |
45 | it('should work and respect the "output.filename" default value option', async () => {
46 | const nanoid = customAlphabet("1234567890abcdef", 10);
47 | const compiler = getCompiler(
48 | "./chunks/entry.js",
49 | {},
50 | {
51 | output: {
52 | path: path.resolve(__dirname, "./outputs", `test_${nanoid()}`),
53 | chunkFilename: "[name].chunk.js",
54 | publicPath: "",
55 | },
56 | module: {
57 | rules: [
58 | {
59 | test: /worker\.js$/i,
60 | rules: [
61 | {
62 | loader: path.resolve(__dirname, "../src"),
63 | },
64 | ],
65 | },
66 | ],
67 | },
68 | }
69 | );
70 | const stats = await compile(compiler);
71 | const result = await getResultFromBrowser(stats);
72 |
73 | expect(getModuleSource("./chunks/worker.js", stats)).toMatchSnapshot(
74 | "module"
75 | );
76 | expect(result).toMatchSnapshot("result");
77 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
78 | expect(getErrors(stats)).toMatchSnapshot("errors");
79 | });
80 |
81 | it('should work and respect the "output.filename" option ("string")', async () => {
82 | const nanoid = customAlphabet("1234567890abcdef", 10);
83 | const compiler = getCompiler(
84 | "./chunks/entry.js",
85 | {},
86 | {
87 | output: {
88 | path: path.resolve(__dirname, "./outputs", `test_${nanoid()}`),
89 | filename: "[name].custom.js",
90 | chunkFilename: "[name].chunk.js",
91 | publicPath: "",
92 | },
93 | module: {
94 | rules: [
95 | {
96 | test: /worker\.js$/i,
97 | rules: [
98 | {
99 | loader: path.resolve(__dirname, "../src"),
100 | },
101 | ],
102 | },
103 | ],
104 | },
105 | }
106 | );
107 | const stats = await compile(compiler);
108 | const result = await getResultFromBrowser(stats);
109 |
110 | expect(getModuleSource("./chunks/worker.js", stats)).toMatchSnapshot(
111 | "module"
112 | );
113 | expect(result).toMatchSnapshot("result");
114 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
115 | expect(getErrors(stats)).toMatchSnapshot("errors");
116 | });
117 |
118 | it('should work and respect the "output.filename" option ("function")', async () => {
119 | const nanoid = customAlphabet("1234567890abcdef", 10);
120 | const compiler = getCompiler(
121 | "./chunks/entry.js",
122 | {},
123 | {
124 | output: {
125 | path: path.resolve(__dirname, "./outputs", `test_${nanoid()}`),
126 | filename: (pathData) => {
127 | if (/worker\.js$/.test(pathData.chunk.entryModule.resource)) {
128 | return "[name].custom.worker.js";
129 | }
130 |
131 | return "[name].js";
132 | },
133 | publicPath: "",
134 | },
135 | module: {
136 | rules: [
137 | {
138 | test: /worker\.js$/i,
139 | rules: [
140 | {
141 | loader: path.resolve(__dirname, "../src"),
142 | },
143 | ],
144 | },
145 | ],
146 | },
147 | }
148 | );
149 | const stats = await compile(compiler);
150 | const result = await getResultFromBrowser(stats);
151 |
152 | expect(getModuleSource("./chunks/worker.js", stats)).toMatchSnapshot(
153 | "module"
154 | );
155 | expect(result).toMatchSnapshot("result");
156 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
157 | expect(getErrors(stats)).toMatchSnapshot("errors");
158 | });
159 | });
160 |
--------------------------------------------------------------------------------
/test/fixtures/basic/entry.js:
--------------------------------------------------------------------------------
1 | import Worker from './worker.js';
2 |
3 | const worker = new Worker();
4 |
5 | let result;
6 |
7 | worker.onmessage = function (event) {
8 | if (!result) {
9 | result = document.createElement("div");
10 | result.setAttribute('id', 'result');
11 |
12 | document.body.append(result);
13 | }
14 |
15 | result.innerText = JSON.stringify(event.data)
16 | };
17 |
18 | const button = document.getElementById('button');
19 |
20 | button.addEventListener('click', () => {
21 | worker.postMessage({ postMessage: true })
22 | });
23 |
--------------------------------------------------------------------------------
/test/fixtures/basic/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Webpack App
6 |
7 |
8 |
9 |
10 | Run Action
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/test/fixtures/basic/worker.js:
--------------------------------------------------------------------------------
1 | onmessage = function(event) {
2 | const workerResult = event.data;
3 |
4 | workerResult.onmessage = true;
5 |
6 | postMessage(workerResult);
7 | };
8 |
--------------------------------------------------------------------------------
/test/fixtures/chunks/chunk.js:
--------------------------------------------------------------------------------
1 | export function returnTrue() {
2 | return true;
3 | }
4 |
--------------------------------------------------------------------------------
/test/fixtures/chunks/entry.js:
--------------------------------------------------------------------------------
1 | import Worker from './worker.js';
2 |
3 | const worker = new Worker();
4 |
5 | let result;
6 |
7 | worker.onmessage = function (event) {
8 | if (!result) {
9 | result = document.createElement("div");
10 | result.setAttribute('id', 'result');
11 |
12 | document.body.append(result);
13 | }
14 |
15 | result.innerText = JSON.stringify(event.data)
16 | };
17 |
18 | const button = document.getElementById('button');
19 |
20 | button.addEventListener('click', () => {
21 | worker.postMessage({ postMessage: true })
22 | });
23 |
--------------------------------------------------------------------------------
/test/fixtures/chunks/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Webpack App
6 |
7 |
8 |
9 |
10 | Run Action
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/test/fixtures/chunks/worker.js:
--------------------------------------------------------------------------------
1 | async function loadChunk() {
2 | return import(/* webpackMode: "lazy" */ './chunk');
3 | }
4 |
5 | onmessage = async function(event) {
6 | const { returnTrue } = await loadChunk();
7 |
8 | const workerResult = event.data;
9 |
10 | workerResult.onmessage = returnTrue();
11 |
12 | postMessage(workerResult);
13 | };
14 |
--------------------------------------------------------------------------------
/test/fixtures/external/entry.js:
--------------------------------------------------------------------------------
1 | import Worker from './worker.js';
2 |
3 | const worker = new Worker();
4 |
5 | let result;
6 |
7 | worker.onmessage = function (event) {
8 | if (!result) {
9 | result = document.createElement("div");
10 | result.setAttribute('id', 'result');
11 |
12 | document.body.append(result);
13 | }
14 |
15 | result.innerText = JSON.stringify(event.data)
16 | };
17 |
18 | const button = document.getElementById('button');
19 |
20 | button.addEventListener('click', () => {
21 | worker.postMessage({ postMessage: true })
22 | });
23 |
--------------------------------------------------------------------------------
/test/fixtures/external/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Webpack App
6 |
7 |
8 |
9 |
10 | Run Action
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/test/fixtures/external/worker.js:
--------------------------------------------------------------------------------
1 | import foo from 'my-custom-module';
2 |
3 | onmessage = function(event) {
4 | const workerResult = event.data;
5 |
6 | workerResult.onmessage = true;
7 |
8 | postMessage(workerResult);
9 | };
10 |
--------------------------------------------------------------------------------
/test/fixtures/name/TypeDetection.js:
--------------------------------------------------------------------------------
1 | onmessage = function(event) {
2 | const workerResult = event.data;
3 |
4 | workerResult.onmessage = true;
5 |
6 | postMessage(workerResult);
7 | };
8 |
--------------------------------------------------------------------------------
/test/fixtures/name/entry.js:
--------------------------------------------------------------------------------
1 | import Worker from './TypeDetection.js';
2 |
3 | const worker = new Worker();
4 |
5 | let result;
6 |
7 | worker.onmessage = function (event) {
8 | if (!result) {
9 | result = document.createElement("div");
10 | result.setAttribute('id', 'result');
11 |
12 | document.body.append(result);
13 | }
14 |
15 | result.innerText = JSON.stringify(event.data)
16 | };
17 |
18 | const button = document.getElementById('button');
19 |
20 | button.addEventListener('click', () => {
21 | worker.postMessage({ postMessage: true })
22 | });
23 |
--------------------------------------------------------------------------------
/test/fixtures/name/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Webpack App
6 |
7 |
8 |
9 |
10 | Run Action
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/test/fixtures/nodejs-core-modules/entry.js:
--------------------------------------------------------------------------------
1 | const Worker = require('./worker.js');
2 |
--------------------------------------------------------------------------------
/test/fixtures/nodejs-core-modules/worker.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs');
2 |
--------------------------------------------------------------------------------
/test/fixtures/query/entry.js:
--------------------------------------------------------------------------------
1 | import Worker from '!../../../src?filename=test.worker.js!./my-worker-name.js';
2 |
3 | const worker = new Worker();
4 |
5 | let result;
6 |
7 | worker.onmessage = function (event) {
8 | if (!result) {
9 | result = document.createElement("div");
10 | result.setAttribute('id', 'result');
11 |
12 | document.body.append(result);
13 | }
14 |
15 | result.innerText = JSON.stringify(event.data)
16 | };
17 |
18 | const button = document.getElementById('button');
19 |
20 | button.addEventListener('click', () => {
21 | worker.postMessage({ postMessage: true })
22 | });
23 |
--------------------------------------------------------------------------------
/test/fixtures/query/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Webpack App
6 |
7 |
8 |
9 |
10 | Run Action
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/test/fixtures/query/my-worker-name.js:
--------------------------------------------------------------------------------
1 | onmessage = function(event) {
2 | const workerResult = event.data;
3 |
4 | workerResult.onmessage = true;
5 |
6 | postMessage(workerResult);
7 | };
8 |
--------------------------------------------------------------------------------
/test/fixtures/wasm/add.wasm:
--------------------------------------------------------------------------------
1 | asm ` add
2 | j name add
lhsrhs
--------------------------------------------------------------------------------
/test/fixtures/wasm/entry.js:
--------------------------------------------------------------------------------
1 | import Worker from './worker';
2 |
3 | const worker = new Worker();
4 |
5 | let result;
6 |
7 | worker.onmessage = function (event) {
8 | if (!result) {
9 | result = document.createElement("div");
10 | result.setAttribute('id', 'result');
11 |
12 | document.body.append(result);
13 | }
14 |
15 | result.innerText = JSON.stringify(event.data)
16 | };
17 |
18 | const button = document.getElementById('button');
19 |
20 | button.addEventListener('click', () => {
21 | worker.postMessage({ postMessage: true })
22 | });
23 |
--------------------------------------------------------------------------------
/test/fixtures/wasm/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Webpack App
6 |
7 |
8 |
9 |
10 | Run Action
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/test/fixtures/wasm/worker.js:
--------------------------------------------------------------------------------
1 | onmessage = async function(event) {
2 | const workerResult = event.data;
3 |
4 | const wasm = await import('./add.wasm');
5 |
6 | workerResult.onmessage = wasm.add(10, 20);
7 |
8 | postMessage(workerResult);
9 | };
10 |
--------------------------------------------------------------------------------
/test/helpers/compile.js:
--------------------------------------------------------------------------------
1 | export default (compiler) =>
2 | new Promise((resolve, reject) => {
3 | compiler.run((error, stats) => {
4 | if (error) {
5 | return reject(error);
6 | }
7 |
8 | return resolve(stats);
9 | });
10 | });
11 |
--------------------------------------------------------------------------------
/test/helpers/execute.js:
--------------------------------------------------------------------------------
1 | import Module from "module";
2 | import path from "path";
3 |
4 | const parentModule = module;
5 |
6 | export default (code) => {
7 | const resource = "test.js";
8 | const module = new Module(resource, parentModule);
9 | // eslint-disable-next-line no-underscore-dangle
10 | module.paths = Module._nodeModulePaths(
11 | path.resolve(__dirname, "../fixtures")
12 | );
13 | module.filename = resource;
14 |
15 | // eslint-disable-next-line no-underscore-dangle
16 | module._compile(
17 | `let __export__;${code};module.exports = __export__;`,
18 | resource
19 | );
20 |
21 | return module.exports;
22 | };
23 |
--------------------------------------------------------------------------------
/test/helpers/getCompiler.js:
--------------------------------------------------------------------------------
1 | import path from "path";
2 |
3 | import webpack from "webpack";
4 | import { customAlphabet } from "nanoid";
5 | import HtmlWebpackPlugin from "html-webpack-plugin";
6 |
7 | export default (fixture, loaderOptions = {}, config = {}) => {
8 | const nanoid = customAlphabet("1234567890abcdef", 10);
9 |
10 | const fullConfig = {
11 | mode: "development",
12 | devtool: config.devtool || false,
13 | context: path.resolve(__dirname, "../fixtures"),
14 | entry: path.resolve(__dirname, "../fixtures", fixture),
15 | output: {
16 | path: path.resolve(__dirname, "../outputs", `test_${nanoid()}`),
17 | filename: "[name].bundle.js",
18 | chunkFilename: "[name].chunk.js",
19 | publicPath: "",
20 | },
21 | module: {
22 | rules: [
23 | {
24 | test: /(worker|TypeDetection)\.js$/i,
25 | rules: [
26 | {
27 | loader: path.resolve(__dirname, "../../src"),
28 | options: { filename: "test.worker.js", ...loaderOptions },
29 | },
30 | ],
31 | },
32 | ],
33 | },
34 | plugins: [
35 | new HtmlWebpackPlugin({
36 | template: path.resolve(
37 | __dirname,
38 | "../fixtures",
39 | path.dirname(fixture),
40 | "index.html"
41 | ),
42 | }),
43 | ],
44 | ...config,
45 | };
46 |
47 | if (webpack.version[0] === "5") {
48 | if (!fullConfig.experiments) {
49 | fullConfig.experiments = {};
50 | }
51 |
52 | fullConfig.experiments.asyncWebAssembly = true;
53 | }
54 |
55 | return webpack(fullConfig);
56 | };
57 |
--------------------------------------------------------------------------------
/test/helpers/getErrors.js:
--------------------------------------------------------------------------------
1 | import normalizeErrors from "./normalizeErrors";
2 |
3 | export default (stats) => normalizeErrors(stats.compilation.errors);
4 |
--------------------------------------------------------------------------------
/test/helpers/getModuleSource.js:
--------------------------------------------------------------------------------
1 | export default (id, stats) => {
2 | const { modules } = stats.toJson({ source: true });
3 | const module = modules.find((m) => m.name.endsWith(id));
4 |
5 | return module.source;
6 | };
7 |
--------------------------------------------------------------------------------
/test/helpers/getResultFromBrowser.js:
--------------------------------------------------------------------------------
1 | import path from "path";
2 |
3 | import getPort from "get-port";
4 | import express from "express";
5 | import puppeteer from "puppeteer";
6 |
7 | export default async function getResultFromBrowser(stats) {
8 | const assets = Object.entries(stats.compilation.assets);
9 | const app = express();
10 | const port = await getPort();
11 | const server = app.listen(port);
12 |
13 | app.use(
14 | "/public-path-static",
15 | express.static(stats.compilation.outputOptions.path)
16 | );
17 | app.use(
18 | "/public-path-static-other",
19 | express.static(stats.compilation.outputOptions.path)
20 | );
21 |
22 | for (const asset of assets) {
23 | let [route] = asset;
24 | [route] = route.split("?");
25 |
26 | const existsAt = path.resolve(stats.compilation.outputOptions.path, route);
27 |
28 | if (route === "index.html") {
29 | app.get("/", (req, res) => {
30 | res.sendFile(existsAt);
31 | });
32 | } else {
33 | app.get(`/${route}`, (req, res) => {
34 | res.sendFile(existsAt);
35 | });
36 | }
37 | }
38 |
39 | const browser = await puppeteer.launch();
40 | const page = await browser.newPage();
41 |
42 | page
43 | .on("console", (message) =>
44 | // eslint-disable-next-line no-console
45 | console.log(message)
46 | )
47 | .on("pageerror", ({ message }) =>
48 | // eslint-disable-next-line no-console
49 | console.log(message)
50 | )
51 | // .on('response', (response) =>
52 | // // eslint-disable-next-line no-console
53 | // console.log(`${response.status()} ${response.url()}`)
54 | // )
55 | .on("requestfailed", (request) =>
56 | // eslint-disable-next-line no-console
57 | console.log(`${request.failure().errorText} ${request.url()}`)
58 | );
59 |
60 | await page.goto(`http://127.0.0.1:${port}/`);
61 | await page.waitForSelector("button", { timeout: 90000 });
62 | await page.click("button");
63 | await page.waitForSelector("#result", { timeout: 90000 });
64 |
65 | const addedFromWorkerText = await page.$eval(
66 | "#result",
67 | (el) => el.textContent
68 | );
69 |
70 | browser.close();
71 | server.close();
72 |
73 | return addedFromWorkerText;
74 | }
75 |
--------------------------------------------------------------------------------
/test/helpers/getWarnings.js:
--------------------------------------------------------------------------------
1 | import normalizeErrors from "./normalizeErrors";
2 |
3 | export default (stats) => normalizeErrors(stats.compilation.warnings);
4 |
--------------------------------------------------------------------------------
/test/helpers/index.js:
--------------------------------------------------------------------------------
1 | import compile from "./compile";
2 | import execute from "./execute";
3 | import getCompiler from "./getCompiler";
4 | import getErrors from "./getErrors";
5 | import getModuleSource from "./getModuleSource";
6 | import getResultFromBrowser from "./getResultFromBrowser";
7 | import getWarnings from "./getWarnings";
8 | import normalizeErrors from "./normalizeErrors";
9 | import readAsset from "./readAsset";
10 | import readsAssets from "./readAssets";
11 |
12 | export {
13 | compile,
14 | execute,
15 | getCompiler,
16 | getErrors,
17 | getModuleSource,
18 | getResultFromBrowser,
19 | getWarnings,
20 | normalizeErrors,
21 | readAsset,
22 | readsAssets,
23 | };
24 |
--------------------------------------------------------------------------------
/test/helpers/normalizeErrors.js:
--------------------------------------------------------------------------------
1 | function removeCWD(str) {
2 | const isWin = process.platform === "win32";
3 | let cwd = process.cwd();
4 |
5 | if (isWin) {
6 | // eslint-disable-next-line no-param-reassign
7 | str = str.replace(/\\/g, "/");
8 | // eslint-disable-next-line no-param-reassign
9 | cwd = cwd.replace(/\\/g, "/");
10 | }
11 |
12 | return str.replace(new RegExp(cwd, "g"), "");
13 | }
14 |
15 | export default (errors) =>
16 | errors.map((error) =>
17 | removeCWD(error.toString().split("\n").slice(0, 2).join("\n"))
18 | );
19 |
--------------------------------------------------------------------------------
/test/helpers/readAsset.js:
--------------------------------------------------------------------------------
1 | import path from "path";
2 |
3 | export default (asset, compiler, stats) => {
4 | const usedFs = compiler.outputFileSystem;
5 | const outputPath = stats.compilation.outputOptions.path;
6 |
7 | let data = "";
8 | let targetFile = asset;
9 |
10 | const queryStringIdx = targetFile.indexOf("?");
11 |
12 | if (queryStringIdx >= 0) {
13 | targetFile = targetFile.substr(0, queryStringIdx);
14 | }
15 |
16 | try {
17 | data = usedFs.readFileSync(path.join(outputPath, targetFile)).toString();
18 | } catch (error) {
19 | data = error.toString();
20 | }
21 |
22 | return data;
23 | };
24 |
--------------------------------------------------------------------------------
/test/helpers/readAssets.js:
--------------------------------------------------------------------------------
1 | import readAsset from "./readAsset";
2 |
3 | export default function readAssets(compiler, stats) {
4 | const assets = {};
5 |
6 | Object.keys(stats.compilation.assets).forEach((asset) => {
7 | assets[asset] = readAsset(asset, compiler, stats);
8 | });
9 |
10 | return assets;
11 | }
12 |
--------------------------------------------------------------------------------
/test/inline-option.test.js:
--------------------------------------------------------------------------------
1 | import {
2 | compile,
3 | getCompiler,
4 | getErrors,
5 | getModuleSource,
6 | getResultFromBrowser,
7 | getWarnings,
8 | } from "./helpers";
9 |
10 | describe('"inline" option', () => {
11 | it("should not work by default", async () => {
12 | const compiler = getCompiler("./basic/entry.js");
13 | const stats = await compile(compiler);
14 | const result = await getResultFromBrowser(stats);
15 |
16 | expect(getModuleSource("./basic/worker.js", stats)).toMatchSnapshot(
17 | "module"
18 | );
19 | expect(stats.compilation.assets["test.worker.js"]).toBeDefined();
20 | expect(result).toMatchSnapshot("result");
21 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
22 | expect(getErrors(stats)).toMatchSnapshot("errors");
23 | });
24 |
25 | it('should work with "no-fallback" value', async () => {
26 | const compiler = getCompiler("./basic/entry.js", { inline: "no-fallback" });
27 | const stats = await compile(compiler);
28 | const result = await getResultFromBrowser(stats);
29 | const moduleSource = getModuleSource("./basic/worker.js", stats);
30 |
31 | expect(moduleSource.indexOf("inline.js") > 0).toBe(true);
32 | expect(
33 | moduleSource.indexOf('__webpack_public_path__ + "test.worker.js"') === -1
34 | ).toBe(true);
35 | expect(stats.compilation.assets["test.worker.js"]).toBeUndefined();
36 | expect(result).toMatchSnapshot("result");
37 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
38 | expect(getErrors(stats)).toMatchSnapshot("errors");
39 | });
40 |
41 | it('should work with "no-fallback" value and the "devtool" option ("source-map" value)', async () => {
42 | const compiler = getCompiler(
43 | "./basic/entry.js",
44 | { inline: "no-fallback" },
45 | { devtool: "source-map" }
46 | );
47 | const stats = await compile(compiler);
48 | const result = await getResultFromBrowser(stats);
49 | const moduleSource = getModuleSource("./basic/worker.js", stats);
50 |
51 | expect(moduleSource.indexOf("inline.js") > 0).toBe(true);
52 | expect(
53 | moduleSource.indexOf('__webpack_public_path__ + "test.worker.js"') === -1
54 | ).toBe(true);
55 | expect(
56 | moduleSource.indexOf('sourceMappingURL=test.worker.js.map"') === -1
57 | ).toBe(true);
58 | expect(stats.compilation.assets["test.worker.js"]).toBeUndefined();
59 | expect(stats.compilation.assets["test.worker.js.map"]).toBeUndefined();
60 | expect(result).toMatchSnapshot("result");
61 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
62 | expect(getErrors(stats)).toMatchSnapshot("errors");
63 | });
64 |
65 | it('should work with "no-fallback" value and the "devtool" option ("eval-source-map" value)', async () => {
66 | const compiler = getCompiler(
67 | "./basic/entry.js",
68 | { inline: "no-fallback" },
69 | { devtool: "eval-source-map" }
70 | );
71 | const stats = await compile(compiler);
72 | const result = await getResultFromBrowser(stats);
73 | const moduleSource = getModuleSource("./basic/worker.js", stats);
74 | const sourceUrlInternalIndex = moduleSource.indexOf(
75 | "sourceURL=webpack-internal:///./basic/worker.js"
76 | );
77 |
78 | expect(moduleSource.indexOf("inline.js") > 0).toBe(true);
79 | expect(
80 | moduleSource.indexOf('__webpack_public_path__ + "test.worker.js"') === -1
81 | ).toBe(true);
82 | expect(
83 | moduleSource.indexOf(
84 | "sourceMappingURL=data:application/json;charset=utf-8;base64,"
85 | ) === -1
86 | ).toBe(true);
87 | expect(sourceUrlInternalIndex === -1).toBe(true);
88 | expect(stats.compilation.assets["test.worker.js"]).toBeUndefined();
89 | expect(stats.compilation.assets["test.worker.js.map"]).toBeUndefined();
90 | expect(result).toMatchSnapshot("result");
91 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
92 | expect(getErrors(stats)).toMatchSnapshot("errors");
93 | });
94 |
95 | it('should work with "no-fallback" value and the "devtool" option ("source-map" value)', async () => {
96 | const compiler = getCompiler(
97 | "./basic/entry.js",
98 | { inline: "no-fallback" },
99 | { devtool: false }
100 | );
101 | const stats = await compile(compiler);
102 | const result = await getResultFromBrowser(stats);
103 | const moduleSource = getModuleSource("./basic/worker.js", stats);
104 |
105 | expect(moduleSource.indexOf("inline.js") > 0).toBe(true);
106 | expect(
107 | moduleSource.indexOf('__webpack_public_path__ + "test.worker.js"') === -1
108 | ).toBe(true);
109 | expect(stats.compilation.assets["test.worker.js"]).toBeUndefined();
110 | expect(stats.compilation.assets["test.worker.js.map"]).toBeUndefined();
111 | expect(result).toMatchSnapshot("result");
112 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
113 | expect(getErrors(stats)).toMatchSnapshot("errors");
114 | });
115 |
116 | it('should work with "fallback" value', async () => {
117 | const compiler = getCompiler("./basic/entry.js", { inline: "fallback" });
118 | const stats = await compile(compiler);
119 | const result = await getResultFromBrowser(stats);
120 | const moduleSource = getModuleSource("./basic/worker.js", stats);
121 |
122 | expect(moduleSource.indexOf("inline.js") > 0).toBe(true);
123 | expect(
124 | moduleSource.indexOf('__webpack_public_path__ + "test.worker.js"') > 0
125 | ).toBe(true);
126 | expect(stats.compilation.assets["test.worker.js"]).toBeDefined();
127 | expect(result).toMatchSnapshot("result");
128 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
129 | expect(getErrors(stats)).toMatchSnapshot("errors");
130 | });
131 |
132 | it('should work with "fallback" value and the "devtool" option ("source-map" value)', async () => {
133 | const compiler = getCompiler(
134 | "./basic/entry.js",
135 | { inline: "fallback" },
136 | { devtool: "source-map" }
137 | );
138 | const stats = await compile(compiler);
139 | const result = await getResultFromBrowser(stats);
140 | const moduleSource = getModuleSource("./basic/worker.js", stats);
141 |
142 | expect(moduleSource.indexOf("inline.js") > 0).toBe(true);
143 | expect(
144 | moduleSource.indexOf('__webpack_public_path__ + "test.worker.js"') > 0
145 | ).toBe(true);
146 | expect(stats.compilation.assets["test.worker.js"]).toBeDefined();
147 | expect(stats.compilation.assets["test.worker.js.map"]).toBeDefined();
148 | expect(result).toMatchSnapshot("result");
149 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
150 | expect(getErrors(stats)).toMatchSnapshot("errors");
151 | });
152 |
153 | it('should work with "fallback" value and the "devtool" option ("source-map" value)', async () => {
154 | const compiler = getCompiler(
155 | "./basic/entry.js",
156 | { inline: "fallback" },
157 | { devtool: false }
158 | );
159 | const stats = await compile(compiler);
160 | const result = await getResultFromBrowser(stats);
161 | const moduleSource = getModuleSource("./basic/worker.js", stats);
162 |
163 | expect(moduleSource.indexOf("inline.js") > 0).toBe(true);
164 | expect(
165 | moduleSource.indexOf('__webpack_public_path__ + "test.worker.js"') > 0
166 | ).toBe(true);
167 | expect(stats.compilation.assets["test.worker.js"]).toBeDefined();
168 | expect(stats.compilation.assets["test.worker.js.map"]).toBeUndefined();
169 | expect(result).toMatchSnapshot("result");
170 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
171 | expect(getErrors(stats)).toMatchSnapshot("errors");
172 | });
173 |
174 | it('should work with "no-fallback" value and "esModule" with "false" value', async () => {
175 | const compiler = getCompiler("./basic/entry.js", {
176 | inline: "no-fallback",
177 | esModule: false,
178 | });
179 | const stats = await compile(compiler);
180 | const result = await getResultFromBrowser(stats);
181 | const moduleSource = getModuleSource("./basic/worker.js", stats);
182 |
183 | expect(moduleSource.indexOf("inline.js") > 0).toBe(true);
184 | expect(
185 | moduleSource.indexOf('__webpack_public_path__ + "test.worker.js"') === -1
186 | ).toBe(true);
187 | expect(stats.compilation.assets["test.worker.js"]).toBeUndefined();
188 | expect(result).toMatchSnapshot("result");
189 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
190 | expect(getErrors(stats)).toMatchSnapshot("errors");
191 | });
192 |
193 | it('should work with "no-fallback" value and "esModule" with "true" value', async () => {
194 | const compiler = getCompiler("./basic/entry.js", {
195 | inline: "no-fallback",
196 | esModule: true,
197 | });
198 | const stats = await compile(compiler);
199 | const result = await getResultFromBrowser(stats);
200 | const moduleSource = getModuleSource("./basic/worker.js", stats);
201 |
202 | expect(moduleSource.indexOf("inline.js") > 0).toBe(true);
203 | expect(
204 | moduleSource.indexOf('__webpack_public_path__ + "test.worker.js"') === -1
205 | ).toBe(true);
206 | expect(stats.compilation.assets["test.worker.js"]).toBeUndefined();
207 | expect(result).toMatchSnapshot("result");
208 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
209 | expect(getErrors(stats)).toMatchSnapshot("errors");
210 | });
211 |
212 | it('should work with "fallback" value and "esModule" with "false" value', async () => {
213 | const compiler = getCompiler("./basic/entry.js", {
214 | inline: "fallback",
215 | esModule: false,
216 | });
217 | const stats = await compile(compiler);
218 | const result = await getResultFromBrowser(stats);
219 | const moduleSource = getModuleSource("./basic/worker.js", stats);
220 |
221 | expect(moduleSource.indexOf("inline.js") > 0).toBe(true);
222 | expect(
223 | moduleSource.indexOf('__webpack_public_path__ + "test.worker.js"') > 0
224 | ).toBe(true);
225 | expect(stats.compilation.assets["test.worker.js"]).toBeDefined();
226 | expect(result).toMatchSnapshot("result");
227 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
228 | expect(getErrors(stats)).toMatchSnapshot("errors");
229 | });
230 |
231 | it('should work with "fallback" value and "esModule" with "true" value', async () => {
232 | const compiler = getCompiler("./basic/entry.js", {
233 | inline: "fallback",
234 | esModule: true,
235 | });
236 | const stats = await compile(compiler);
237 | const result = await getResultFromBrowser(stats);
238 | const moduleSource = getModuleSource("./basic/worker.js", stats);
239 |
240 | expect(moduleSource.indexOf("inline.js") > 0).toBe(true);
241 | expect(
242 | moduleSource.indexOf('__webpack_public_path__ + "test.worker.js"') > 0
243 | ).toBe(true);
244 | expect(stats.compilation.assets["test.worker.js"]).toBeDefined();
245 | expect(result).toMatchSnapshot("result");
246 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
247 | expect(getErrors(stats)).toMatchSnapshot("errors");
248 | });
249 | });
250 |
--------------------------------------------------------------------------------
/test/loader.test.js:
--------------------------------------------------------------------------------
1 | import {
2 | compile,
3 | getCompiler,
4 | getErrors,
5 | getModuleSource,
6 | getResultFromBrowser,
7 | getWarnings,
8 | } from "./helpers";
9 |
10 | describe("worker-loader", () => {
11 | it("should work", async () => {
12 | const compiler = getCompiler("./basic/entry.js");
13 | const stats = await compile(compiler);
14 | const result = await getResultFromBrowser(stats);
15 |
16 | expect(getModuleSource("./basic/worker.js", stats)).toMatchSnapshot(
17 | "module"
18 | );
19 | expect(result).toMatchSnapshot("result");
20 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
21 | expect(getErrors(stats)).toMatchSnapshot("errors");
22 | });
23 |
24 | it("should work with inline syntax", async () => {
25 | const compiler = getCompiler("./query/entry.js");
26 | const stats = await compile(compiler);
27 | const result = await getResultFromBrowser(stats);
28 |
29 | expect(getModuleSource("./query/my-worker-name.js", stats)).toMatchSnapshot(
30 | "module"
31 | );
32 | expect(result).toMatchSnapshot("result");
33 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
34 | expect(getErrors(stats)).toMatchSnapshot("errors");
35 | });
36 |
37 | it("should work with WASM", async () => {
38 | const compiler = getCompiler("./wasm/entry.js");
39 | const stats = await compile(compiler);
40 | const result = await getResultFromBrowser(stats);
41 |
42 | expect(getModuleSource("./wasm/worker.js", stats)).toMatchSnapshot(
43 | "module"
44 | );
45 | expect(result).toMatchSnapshot("result");
46 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
47 | expect(getErrors(stats)).toMatchSnapshot("errors");
48 | });
49 |
50 | it("should work with async chunks", async () => {
51 | const compiler = getCompiler("./chunks/entry.js");
52 | const stats = await compile(compiler);
53 | const result = await getResultFromBrowser(stats);
54 |
55 | expect(getModuleSource("./chunks/worker.js", stats)).toMatchSnapshot(
56 | "module"
57 | );
58 | expect(result).toMatchSnapshot("result");
59 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
60 | expect(getErrors(stats)).toMatchSnapshot("errors");
61 | });
62 |
63 | it('should work with "externals"', async () => {
64 | const compiler = getCompiler(
65 | "./external/entry.js",
66 | {},
67 | {
68 | externals: {
69 | "my-custom-module": "navigator",
70 | },
71 | }
72 | );
73 | const stats = await compile(compiler);
74 | const result = await getResultFromBrowser(stats);
75 |
76 | expect(getModuleSource("./external/worker.js", stats)).toMatchSnapshot(
77 | "module"
78 | );
79 | expect(result).toMatchSnapshot("result");
80 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
81 | expect(getErrors(stats)).toMatchSnapshot("errors");
82 | });
83 |
84 | it('should work and respect the "devtool" option ("source-map" value)', async () => {
85 | const compiler = getCompiler(
86 | "./basic/entry.js",
87 | {},
88 | { devtool: "source-map" }
89 | );
90 | const stats = await compile(compiler);
91 | const result = await getResultFromBrowser(stats);
92 |
93 | expect(getModuleSource("./basic/worker.js", stats)).toMatchSnapshot(
94 | "module"
95 | );
96 | expect(stats.compilation.assets["test.worker.js.map"]).toBeDefined();
97 | expect(result).toMatchSnapshot("result");
98 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
99 | expect(getErrors(stats)).toMatchSnapshot("errors");
100 | });
101 |
102 | it('should work and respect the "devtool" option ("false" value)', async () => {
103 | const compiler = getCompiler("./basic/entry.js", {}, { devtool: false });
104 | const stats = await compile(compiler);
105 | const result = await getResultFromBrowser(stats);
106 |
107 | expect(getModuleSource("./basic/worker.js", stats)).toMatchSnapshot(
108 | "module"
109 | );
110 | expect(stats.compilation.assets["test.worker.js.map"]).toBeUndefined();
111 | expect(result).toMatchSnapshot("result");
112 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
113 | expect(getErrors(stats)).toMatchSnapshot("errors");
114 | });
115 |
116 | it("should work and have the same base file name as the source files", async () => {
117 | const compiler = getCompiler("./name/entry.js", {
118 | filename: "[name].worker.js",
119 | });
120 | const stats = await compile(compiler);
121 | const result = await getResultFromBrowser(stats);
122 |
123 | expect(getModuleSource("./name/TypeDetection.js", stats)).toMatchSnapshot(
124 | "module"
125 | );
126 | expect(result).toMatchSnapshot("result");
127 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
128 | expect(getErrors(stats)).toMatchSnapshot("errors");
129 | });
130 | });
131 |
--------------------------------------------------------------------------------
/test/publicPath.test.js:
--------------------------------------------------------------------------------
1 | import path from "path";
2 |
3 | import { customAlphabet } from "nanoid";
4 |
5 | import {
6 | compile,
7 | getCompiler,
8 | getErrors,
9 | getModuleSource,
10 | getResultFromBrowser,
11 | getWarnings,
12 | } from "./helpers";
13 |
14 | describe('"publicPath" option', () => {
15 | it('should work and use "__webpack_public_path__" by default', async () => {
16 | const compiler = getCompiler("./chunks/entry.js");
17 | const stats = await compile(compiler);
18 | const result = await getResultFromBrowser(stats);
19 |
20 | expect(getModuleSource("./chunks/worker.js", stats)).toMatchSnapshot(
21 | "module"
22 | );
23 | expect(result).toMatchSnapshot("result");
24 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
25 | expect(getErrors(stats)).toMatchSnapshot("errors");
26 | });
27 |
28 | it('should work and respect the "publicPath" option ("string")', async () => {
29 | const compiler = getCompiler("./chunks/entry.js", {
30 | publicPath: "/public-path-static/",
31 | });
32 | const stats = await compile(compiler);
33 | const result = await getResultFromBrowser(stats);
34 |
35 | expect(getModuleSource("./chunks/worker.js", stats)).toMatchSnapshot(
36 | "module"
37 | );
38 | expect(result).toMatchSnapshot("result");
39 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
40 | expect(getErrors(stats)).toMatchSnapshot("errors");
41 | });
42 |
43 | it('should work and respect the "publicPath" option ("function")', async () => {
44 | const compiler = getCompiler("./chunks/entry.js", {
45 | publicPath: () => `/public-path-static/`,
46 | });
47 | const stats = await compile(compiler);
48 | const result = await getResultFromBrowser(stats);
49 |
50 | expect(getModuleSource("./chunks/worker.js", stats)).toMatchSnapshot(
51 | "module"
52 | );
53 | expect(result).toMatchSnapshot("result");
54 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
55 | expect(getErrors(stats)).toMatchSnapshot("errors");
56 | });
57 |
58 | it('should work and respect the "output.publicPath" option default value', async () => {
59 | const nanoid = customAlphabet("1234567890abcdef", 10);
60 | const compiler = getCompiler(
61 | "./chunks/entry.js",
62 | {},
63 | {
64 | output: {
65 | path: path.resolve(__dirname, "./outputs", `test_${nanoid()}`),
66 | filename: "[name].bundle.js",
67 | chunkFilename: "[name].chunk.js",
68 | publicPath: "",
69 | },
70 | }
71 | );
72 | const stats = await compile(compiler);
73 | const result = await getResultFromBrowser(stats);
74 |
75 | expect(getModuleSource("./chunks/worker.js", stats)).toMatchSnapshot(
76 | "module"
77 | );
78 | expect(result).toMatchSnapshot("result");
79 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
80 | expect(getErrors(stats)).toMatchSnapshot("errors");
81 | });
82 |
83 | it('should work and respect the "output.publicPath" option value ("string")', async () => {
84 | const nanoid = customAlphabet("1234567890abcdef", 10);
85 | const compiler = getCompiler(
86 | "./chunks/entry.js",
87 | {},
88 | {
89 | output: {
90 | publicPath: "/public-path-static/",
91 | path: path.resolve(__dirname, "./outputs", `test_${nanoid()}`),
92 | filename: "[name].bundle.js",
93 | chunkFilename: "[name].chunk.js",
94 | },
95 | }
96 | );
97 | const stats = await compile(compiler);
98 | const result = await getResultFromBrowser(stats);
99 |
100 | expect(getModuleSource("./chunks/worker.js", stats)).toMatchSnapshot(
101 | "module"
102 | );
103 | expect(result).toMatchSnapshot("result");
104 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
105 | expect(getErrors(stats)).toMatchSnapshot("errors");
106 | });
107 |
108 | it('should work and respect the "output.publicPath" option value ("function")', async () => {
109 | const nanoid = customAlphabet("1234567890abcdef", 10);
110 | const compiler = getCompiler(
111 | "./chunks/entry.js",
112 | {},
113 | {
114 | output: {
115 | publicPath: () => "/public-path-static/",
116 | path: path.resolve(__dirname, "./outputs", `test_${nanoid()}`),
117 | filename: "[name].bundle.js",
118 | chunkFilename: "[name].chunk.js",
119 | },
120 | }
121 | );
122 | const stats = await compile(compiler);
123 | const result = await getResultFromBrowser(stats);
124 |
125 | expect(getModuleSource("./chunks/worker.js", stats)).toMatchSnapshot(
126 | "module"
127 | );
128 | expect(result).toMatchSnapshot("result");
129 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
130 | expect(getErrors(stats)).toMatchSnapshot("errors");
131 | });
132 |
133 | it('should work and respect "filename" and "chunkFilename" option values', async () => {
134 | const nanoid = customAlphabet("1234567890abcdef", 10);
135 | const compiler = getCompiler(
136 | "./chunks/entry.js",
137 | {},
138 | {
139 | module: {
140 | rules: [
141 | {
142 | test: /worker\.js$/i,
143 | rules: [
144 | {
145 | loader: path.resolve(__dirname, "./../src"),
146 | },
147 | ],
148 | },
149 | ],
150 | },
151 | output: {
152 | publicPath: "/public-path-static-other/",
153 | path: path.resolve(__dirname, "./outputs", `test_${nanoid()}`),
154 | filename: "other-static/js/[name].bundle.js",
155 | chunkFilename: "other-static/js/[name].chunk.js",
156 | },
157 | }
158 | );
159 | const stats = await compile(compiler);
160 | const result = await getResultFromBrowser(stats);
161 |
162 | expect(getModuleSource("./chunks/worker.js", stats)).toMatchSnapshot(
163 | "module"
164 | );
165 | expect(result).toMatchSnapshot("result");
166 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
167 | expect(getErrors(stats)).toMatchSnapshot("errors");
168 | });
169 |
170 | it('should work and respect "filename" and "chunkFilename" option values', async () => {
171 | const compiler = getCompiler("./chunks/entry.js", {
172 | publicPath: "/public-path-static-other/",
173 | filename: "other-static/js/[name].worker.js",
174 | chunkFilename: "other-static/js/[name].chunk.worker.js",
175 | });
176 | const stats = await compile(compiler);
177 | const result = await getResultFromBrowser(stats);
178 |
179 | expect(getModuleSource("./chunks/worker.js", stats)).toMatchSnapshot(
180 | "module"
181 | );
182 | expect(result).toMatchSnapshot("result");
183 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
184 | expect(getErrors(stats)).toMatchSnapshot("errors");
185 | });
186 | });
187 |
--------------------------------------------------------------------------------
/test/sourceMapperRegexp.test.js:
--------------------------------------------------------------------------------
1 | import { sourceMappingURLRegex } from "../src/utils";
2 |
3 | describe("source-map-loader", () => {
4 | const cases = [
5 | "/*#sourceMappingURL=absolute-sourceRoot-source-map.map*/",
6 | "/* #sourceMappingURL=absolute-sourceRoot-source-map.map */",
7 | "//#sourceMappingURL=absolute-sourceRoot-source-map.map",
8 | "//@sourceMappingURL=absolute-sourceRoot-source-map.map",
9 | " // #sourceMappingURL=absolute-sourceRoot-source-map.map",
10 | " // # sourceMappingURL = absolute-sourceRoot-source-map.map ",
11 | "// #sourceMappingURL = http://sampledomain.com/external-source-map2.map",
12 | "// #sourceMappingURL = //sampledomain.com/external-source-map2.map",
13 | "// @sourceMappingURL=data:application/source-map;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5saW5lLXNvdXJjZS1tYXAuanMiLCJzb3VyY2VzIjpbImlubGluZS1zb3VyY2UtbWFwLnR4dCJdLCJzb3VyY2VzQ29udGVudCI6WyJ3aXRoIFNvdXJjZU1hcCJdLCJtYXBwaW5ncyI6IkFBQUEifQ==",
14 | `
15 | with SourceMap
16 |
17 | // #sourceMappingURL = /sample-source-map.map
18 | // comment
19 | `,
20 | "onmessage = function(event) {\n const workerResult = event.data;\n\n workerResult.onmessage = true;\n\n postMessage(workerResult);\n};\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9iYXNpYy93b3JrZXIuanM/OGFiZiJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTtBQUNBOztBQUVBOztBQUVBO0FBQ0EiLCJmaWxlIjoiLi9iYXNpYy93b3JrZXIuanMuanMiLCJzb3VyY2VzQ29udGVudCI6WyJvbm1lc3NhZ2UgPSBmdW5jdGlvbihldmVudCkge1xuICBjb25zdCB3b3JrZXJSZXN1bHQgPSBldmVudC5kYXRhO1xuXG4gIHdvcmtlclJlc3VsdC5vbm1lc3NhZ2UgPSB0cnVlO1xuXG4gIHBvc3RNZXNzYWdlKHdvcmtlclJlc3VsdCk7XG59O1xuIl0sInNvdXJjZVJvb3QiOiIifQ==\n//# sourceURL=webpack-internal:///./basic/worker.js\n",
21 | ];
22 |
23 | cases.forEach((item) => {
24 | it(`should work with "${item}" url`, async () => {
25 | const result = item.replace(sourceMappingURLRegex, "REPLASED");
26 |
27 | expect(result.indexOf("REPLASED") !== -1).toBe(true);
28 | expect(result).toMatchSnapshot("result");
29 | });
30 | });
31 | });
32 |
--------------------------------------------------------------------------------
/test/validate-options.test.js:
--------------------------------------------------------------------------------
1 | import { getCompiler, compile } from "./helpers/index";
2 |
3 | describe("validate options", () => {
4 | const tests = {
5 | worker: {
6 | success: [
7 | "Worker",
8 | { type: "Worker" },
9 | { type: "Worker", options: { type: "classic", name: "worker-name" } },
10 | ],
11 | failure: [true, []],
12 | },
13 | publicPath: {
14 | success: ["/assets/", () => "/assets/"],
15 | failure: [true, []],
16 | },
17 | filename: {
18 | success: ["[name].worker.js", () => "[name].worker.js"],
19 | failure: [true, []],
20 | },
21 | chunkFilename: {
22 | success: ["[name].chunk.worker.js"],
23 | failure: [true, []],
24 | },
25 | inline: {
26 | success: ["fallback", "no-fallback"],
27 | failure: [true, "true"],
28 | },
29 | esModule: {
30 | success: [true, false],
31 | failure: ["true"],
32 | },
33 | unknown: {
34 | success: [],
35 | failure: [1, true, false, "test", /test/, [], {}, { foo: "bar" }],
36 | },
37 | };
38 |
39 | function stringifyValue(value) {
40 | if (
41 | Array.isArray(value) ||
42 | (value && typeof value === "object" && value.constructor === Object)
43 | ) {
44 | return JSON.stringify(value);
45 | }
46 |
47 | return value;
48 | }
49 |
50 | async function createTestCase(key, value, type) {
51 | it(`should ${
52 | type === "success" ? "successfully validate" : "throw an error on"
53 | } the "${key}" option with "${stringifyValue(value)}" value`, async () => {
54 | const compiler = getCompiler("./basic/entry.js", { [key]: value });
55 |
56 | let stats;
57 |
58 | try {
59 | stats = await compile(compiler);
60 | } finally {
61 | if (type === "success") {
62 | expect(stats.hasErrors()).toBe(false);
63 | } else if (type === "failure") {
64 | const {
65 | compilation: { errors },
66 | } = stats;
67 |
68 | expect(errors).toHaveLength(1);
69 | expect(() => {
70 | throw new Error(errors[0].error.message);
71 | }).toThrowErrorMatchingSnapshot();
72 | }
73 | }
74 | });
75 | }
76 |
77 | for (const [key, values] of Object.entries(tests)) {
78 | for (const type of Object.keys(values)) {
79 | for (const value of values[type]) {
80 | createTestCase(key, value, type);
81 | }
82 | }
83 | }
84 | });
85 |
--------------------------------------------------------------------------------
/test/worker-option.test.js:
--------------------------------------------------------------------------------
1 | import {
2 | compile,
3 | getCompiler,
4 | getErrors,
5 | getModuleSource,
6 | getResultFromBrowser,
7 | getWarnings,
8 | } from "./helpers";
9 |
10 | describe('"workerType" option', () => {
11 | it('should use "Worker" by default', async () => {
12 | const compiler = getCompiler("./basic/entry.js");
13 | const stats = await compile(compiler);
14 | const result = await getResultFromBrowser(stats);
15 |
16 | expect(getModuleSource("./basic/worker.js", stats)).toMatchSnapshot(
17 | "module"
18 | );
19 | expect(result).toMatchSnapshot("result");
20 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
21 | expect(getErrors(stats)).toMatchSnapshot("errors");
22 | });
23 |
24 | it('should support the "Worker" string value', async () => {
25 | const compiler = getCompiler("./basic/entry.js", { worker: "Worker" });
26 | const stats = await compile(compiler);
27 | const result = await getResultFromBrowser(stats);
28 |
29 | expect(getModuleSource("./basic/worker.js", stats)).toMatchSnapshot(
30 | "module"
31 | );
32 | expect(result).toMatchSnapshot("result");
33 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
34 | expect(getErrors(stats)).toMatchSnapshot("errors");
35 | });
36 |
37 | it('should support the "Worker" object value', async () => {
38 | const compiler = getCompiler("./basic/entry.js", {
39 | worker: {
40 | type: "Worker",
41 | options: {
42 | type: "classic",
43 | name: "worker-name",
44 | },
45 | },
46 | });
47 | const stats = await compile(compiler);
48 | const result = await getResultFromBrowser(stats);
49 |
50 | expect(getModuleSource("./basic/worker.js", stats)).toMatchSnapshot(
51 | "module"
52 | );
53 | expect(result).toMatchSnapshot("result");
54 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
55 | expect(getErrors(stats)).toMatchSnapshot("errors");
56 | });
57 |
58 | it('should support the "Worker" object value for inline workers with fallback', async () => {
59 | const compiler = getCompiler("./basic/entry.js", {
60 | inline: "fallback",
61 | worker: {
62 | type: "Worker",
63 | options: {
64 | type: "classic",
65 | name: "worker-name",
66 | },
67 | },
68 | });
69 | const stats = await compile(compiler);
70 | const result = await getResultFromBrowser(stats);
71 |
72 | const moduleSource = getModuleSource("./basic/worker.js", stats);
73 |
74 | expect(moduleSource.indexOf("inline.js") > 0).toBe(true);
75 | expect(
76 | moduleSource.indexOf('__webpack_public_path__ + "test.worker.js"') > 0
77 | ).toBe(true);
78 | expect(stats.compilation.assets["test.worker.js"]).toBeDefined();
79 | expect(result).toMatchSnapshot("result");
80 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
81 | expect(getErrors(stats)).toMatchSnapshot("errors");
82 | });
83 |
84 | it('should support the "Worker" object value for inline workers without fallback', async () => {
85 | const compiler = getCompiler("./basic/entry.js", {
86 | inline: "no-fallback",
87 | worker: {
88 | type: "Worker",
89 | options: {
90 | type: "classic",
91 | name: "worker-name",
92 | },
93 | },
94 | });
95 | const stats = await compile(compiler);
96 | const result = await getResultFromBrowser(stats);
97 |
98 | const moduleSource = getModuleSource("./basic/worker.js", stats);
99 |
100 | expect(moduleSource.indexOf("inline.js") > 0).toBe(true);
101 | expect(
102 | moduleSource.indexOf('__webpack_public_path__ + "test.worker.js"') === -1
103 | ).toBe(true);
104 | expect(stats.compilation.assets["test.worker.js"]).toBeUndefined();
105 | expect(result).toMatchSnapshot("result");
106 | expect(getWarnings(stats)).toMatchSnapshot("warnings");
107 | expect(getErrors(stats)).toMatchSnapshot("errors");
108 | });
109 | });
110 |
--------------------------------------------------------------------------------