├── .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
├── .prettierrc.js
├── CHANGELOG.md
├── LICENSE
├── README.md
├── babel.config.js
├── commitlint.config.js
├── husky.config.js
├── lint-staged.config.js
├── package-lock.json
├── package.json
├── src
├── cjs.js
├── index.js
└── options.json
└── test
├── __snapshots__
├── esModule-option.test.js.snap
├── loader.test.js.snap
└── validate-options.test.js.snap
├── cjs.test.js
├── esModule-option.test.js
├── fixtures
├── file.txt
├── inline.js
└── simple.js
├── helpers
├── compile.js
├── execute.js
├── getCompiler.js
├── index.js
├── normalizeErrors.js
└── readAsset.js
├── loader.test.js
└── validate-options.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
--------------------------------------------------------------------------------
/.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
5 |
--------------------------------------------------------------------------------
/.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.
7 |
--------------------------------------------------------------------------------
/.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 | "raw-loader": "webpack-contrib/raw-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/raw-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 |
16 |
17 | - Operating System:
18 | - Node Version:
19 | - NPM Version:
20 | - webpack Version:
21 | - raw-loader Version:
22 |
23 | ### Expected Behavior
24 |
25 |
26 |
27 | ### Actual Behavior
28 |
29 |
30 |
31 | ### Code
32 |
33 | ```js
34 | // webpack.config.js
35 | // If your code blocks are over 20 lines, please paste a link to a gist
36 | // (https://gist.github.com).
37 | ```
38 |
39 | ```js
40 | // additional code, HEY YO remove this block if you don't need it
41 | ```
42 |
43 | ### How Do We Reproduce?
44 |
45 |
51 |
--------------------------------------------------------------------------------
/.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 |
16 |
17 | Documentation Is:
18 |
19 |
20 |
21 | - [ ] Missing
22 | - [ ] Needed
23 | - [ ] Confusing
24 | - [ ] Not Sure?
25 |
26 | ### Please Explain in Detail...
27 |
28 | ### Your Proposal for Changes
29 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/FEATURE.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: ✨ Feature Request
3 | about: Suggest an idea for this project
4 | ---
5 |
6 |
16 |
17 | - Operating System:
18 | - Node Version:
19 | - NPM Version:
20 | - webpack Version:
21 | - raw-loader Version:
22 |
23 | ### Feature Proposal
24 |
25 | ### Feature Use Case
26 |
--------------------------------------------------------------------------------
/.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 |
16 |
17 | - Operating System:
18 | - Node Version:
19 | - NPM Version:
20 | - webpack Version:
21 | - raw-loader Version:
22 |
23 | ### Expected Behavior / Situation
24 |
25 | ### Actual Behavior / Situation
26 |
27 | ### Modification Proposal
28 |
--------------------------------------------------------------------------------
/.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 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 [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: raw-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 ${{ env.node-version }}
33 | uses: actions/setup-node@v1
34 | with:
35 | node-version: ${{ env.node-version }}
36 |
37 | - name: Use latest NPM
38 | run: sudo npm i -g npm
39 |
40 | - name: Install dependencies
41 | run: npm ci
42 |
43 | - name: Lint
44 | run: npm run lint
45 |
46 | - name: Security audit
47 | run: npm run security
48 |
49 | - name: Check commit message
50 | uses: wagoid/commitlint-github-action@v1
51 |
52 | test:
53 | name: Test - ${{ matrix.os }} - Node v${{ matrix.node-version }}, Webpack ${{ matrix.webpack-version }}
54 |
55 | strategy:
56 | matrix:
57 | os: [ubuntu-latest, windows-latest, macos-latest]
58 | node-version: [10.x, 12.x, 13.x]
59 | webpack-version: [4, latest]
60 |
61 | runs-on: ${{ matrix.os }}
62 |
63 | steps:
64 | - uses: actions/checkout@v2
65 |
66 | - name: Use Node.js ${{ matrix.node-version }}
67 | uses: actions/setup-node@v1
68 | with:
69 | node-version: ${{ matrix.node-version }}
70 |
71 | - name: Use latest NPM on ubuntu/macos
72 | if: matrix.os == 'ubuntu-latest' || matrix.os == 'macos-latest'
73 | run: sudo npm i -g npm
74 |
75 | - name: Use latest NPM on windows
76 | if: matrix.os == 'windows-latest'
77 | run: npm i -g npm
78 |
79 | - name: Install dependencies
80 | run: npm ci
81 |
82 | - name: Install webpack ${{ matrix.webpack-version }}
83 | run: npm i webpack@${{ matrix.webpack-version }}
84 |
85 | - name: Run tests for webpack version ${{ matrix.webpack-version }}
86 | run: npm run test:coverage -- --ci
87 |
88 | - name: Submit coverage data to codecov
89 | uses: codecov/codecov-action@v1
90 | with:
91 | token: ${{ secrets.CODECOV_TOKEN }}
92 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | logs
2 | *.log
3 | npm-debug.log*
4 | .eslintcache
5 | /coverage
6 | /dist
7 | /local
8 | /reports
9 | /node_modules
10 | .DS_Store
11 | Thumbs.db
12 | .idea
13 | .vscode
14 | *.sublime-project
15 | *.sublime-workspace
16 | *.iml
17 |
--------------------------------------------------------------------------------
/.prettierignore:
--------------------------------------------------------------------------------
1 | /coverage
2 | /dist
3 | /node_modules
4 | /test/fixtures
5 | CHANGELOG.md
--------------------------------------------------------------------------------
/.prettierrc.js:
--------------------------------------------------------------------------------
1 | module.exports = { singleQuote: true };
2 |
--------------------------------------------------------------------------------
/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 | ### [4.0.2](https://github.com/webpack-contrib/raw-loader/compare/v4.0.1...v4.0.2) (2020-10-09)
6 |
7 | ### Chore
8 |
9 | * update `schema-utils`
10 |
11 | ### [4.0.1](https://github.com/webpack-contrib/raw-loader/compare/v4.0.0...v4.0.1) (2020-04-15)
12 |
13 |
14 | ### Chore
15 |
16 | * update deps
17 |
18 | ## [4.0.0](https://github.com/webpack-contrib/raw-loader/compare/v3.1.0...v4.0.0) (2019-11-25)
19 |
20 |
21 | ### Features
22 |
23 | * new esModules option
24 |
25 |
26 | ### BREAKING CHANGES
27 |
28 | * minimum required nodejs version is `10.13.0`
29 |
30 |
31 |
32 | ## [3.1.0](https://github.com/webpack-contrib/raw-loader/compare/v3.0.0...v3.1.0) (2019-07-18)
33 |
34 |
35 | ### Features
36 |
37 | * improved validation error messages ([#85](https://github.com/webpack-contrib/raw-loader/issues/85)) ([6cf76b8](https://github.com/webpack-contrib/raw-loader/commit/6cf76b8))
38 |
39 |
40 |
41 | ## [3.0.0](https://github.com/webpack-contrib/raw-loader/compare/v2.0.0...v3.0.0) (2019-06-05)
42 |
43 |
44 | ### chore
45 |
46 | * **deps:** update ([#81](https://github.com/webpack-contrib/raw-loader/issues/81)) ([d11ff27](https://github.com/webpack-contrib/raw-loader/commit/d11ff27))
47 |
48 |
49 | ### BREAKING CHANGES
50 |
51 | * **deps:** minimum required nodejs version is `8.9.0`
52 |
53 |
54 |
55 |
56 | # [2.0.0](https://github.com/webpack-contrib/raw-loader/compare/v1.0.0...v2.0.0) (2019-03-18)
57 |
58 |
59 | ### Features
60 |
61 | * use ES Module export instead of CommonJS ([#69](https://github.com/webpack-contrib/raw-loader/issues/69)) ([3c7bf2c](https://github.com/webpack-contrib/raw-loader/commit/3c7bf2c))
62 |
63 |
64 | ### BREAKING CHANGES
65 |
66 | * use ES Module export instead of CommonJS ([#69](https://github.com/webpack-contrib/raw-loader/issues/69)) ([3c7bf2c](https://github.com/webpack-contrib/raw-loader/commit/3c7bf2c))
67 |
68 |
69 |
70 |
71 | ## 1.0.0 (2018-12-10)
72 |
73 |
74 | ### Bug Fixes
75 |
76 | * escape invalid characters ([#43](https://github.com/webpack-contrib/raw-loader/issues/43)) ([83f6541](https://github.com/webpack-contrib/raw-loader/commit/83f6541))
77 |
78 | ### Features
79 |
80 | * schema validation ([#58](https://github.com/webpack-contrib/raw-loader/issues/58)) ([4a6da19](https://github.com/webpack-contrib/raw-loader/commit/4a6da19))
81 |
82 |
83 | ### BREAKING CHANGES
84 |
85 | * minimum require `webpack` version is `4`
86 | * minimum require `nodejs` version is `6.9`
87 |
--------------------------------------------------------------------------------
/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 |
9 |
10 | [![npm][npm]][npm-url]
11 | [![node][node]][node-url]
12 | [![deps][deps]][deps-url]
13 | [![tests][tests]][tests-url]
14 | [![coverage][cover]][cover-url]
15 | [![chat][chat]][chat-url]
16 | [![size][size]][size-url]
17 |
18 | # raw-loader
19 |
20 | **DEPREACTED for v5**: please consider migrating to [`asset modules`](https://webpack.js.org/guides/asset-modules/).
21 |
22 | A loader for webpack that allows importing files as a String.
23 |
24 | ## Getting Started
25 |
26 | To begin, you'll need to install `raw-loader`:
27 |
28 | ```console
29 | $ npm install raw-loader --save-dev
30 | ```
31 |
32 | Then add the loader to your `webpack` config. For example:
33 |
34 | **file.js**
35 |
36 | ```js
37 | import txt from './file.txt';
38 | ```
39 |
40 | **webpack.config.js**
41 |
42 | ```js
43 | // webpack.config.js
44 | module.exports = {
45 | module: {
46 | rules: [
47 | {
48 | test: /\.txt$/i,
49 | use: 'raw-loader',
50 | },
51 | ],
52 | },
53 | };
54 | ```
55 |
56 | And run `webpack` via your preferred method.
57 |
58 | ## Options
59 |
60 | | Name | Type | Default | Description |
61 | | :-------------------------: | :---------: | :-----: | :--------------------- |
62 | | **[`esModule`](#esmodule)** | `{Boolean}` | `true` | Uses ES modules syntax |
63 |
64 | ### `esModule`
65 |
66 | Type: `Boolean`
67 | Default: `true`
68 |
69 | By default, `raw-loader` generates JS modules that use the ES modules syntax.
70 | There are some cases in which using ES modules is beneficial, like in the case of [module concatenation](https://webpack.js.org/plugins/module-concatenation-plugin/) and [tree shaking](https://webpack.js.org/guides/tree-shaking/).
71 |
72 | You can enable a CommonJS module syntax using:
73 |
74 | **webpack.config.js**
75 |
76 | ```js
77 | module.exports = {
78 | module: {
79 | rules: [
80 | {
81 | test: /\.txt$/i,
82 | use: [
83 | {
84 | loader: 'raw-loader',
85 | options: {
86 | esModule: false,
87 | },
88 | },
89 | ],
90 | },
91 | ],
92 | },
93 | };
94 | ```
95 |
96 | ## Examples
97 |
98 | ### Inline
99 |
100 | ```js
101 | import txt from 'raw-loader!./file.txt';
102 | ```
103 |
104 | Beware, if you already define loader(s) for extension(s) in `webpack.config.js` you should use:
105 |
106 | ```js
107 | import css from '!!raw-loader!./file.txt'; // Adding `!!` to a request will disable all loaders specified in the configuration
108 | ```
109 |
110 | ## Contributing
111 |
112 | Please take a moment to read our contributing guidelines if you haven't yet done so.
113 |
114 | [CONTRIBUTING](./.github/CONTRIBUTING.md)
115 |
116 | ## License
117 |
118 | [MIT](./LICENSE)
119 |
120 | [npm]: https://img.shields.io/npm/v/raw-loader.svg
121 | [npm-url]: https://npmjs.com/package/raw-loader
122 | [node]: https://img.shields.io/node/v/raw-loader.svg
123 | [node-url]: https://nodejs.org
124 | [deps]: https://david-dm.org/webpack-contrib/raw-loader.svg
125 | [deps-url]: https://david-dm.org/webpack-contrib/raw-loader
126 | [tests]: https://github.com/webpack-contrib/raw-loader/workflows/raw-loader/badge.svg
127 | [tests-url]: https://github.com/webpack-contrib/raw-loader/actions
128 | [cover]: https://codecov.io/gh/webpack-contrib/raw-loader/branch/master/graph/badge.svg
129 | [cover-url]: https://codecov.io/gh/webpack-contrib/raw-loader
130 | [chat]: https://img.shields.io/badge/gitter-webpack%2Fwebpack-brightgreen.svg
131 | [chat-url]: https://gitter.im/webpack/webpack
132 | [size]: https://packagephobia.now.sh/badge?p=raw-loader
133 | [size-url]: https://packagephobia.now.sh/result?p=raw-loader
134 |
--------------------------------------------------------------------------------
/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 | };
19 | };
20 |
--------------------------------------------------------------------------------
/commitlint.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | extends: ['@commitlint/config-conventional'],
3 | };
4 |
--------------------------------------------------------------------------------
/husky.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | hooks: {
3 | 'pre-commit': 'lint-staged',
4 | 'commit-msg': 'commitlint -E HUSKY_GIT_PARAMS',
5 | },
6 | };
7 |
--------------------------------------------------------------------------------
/lint-staged.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | '*.js': ['prettier --write', 'eslint --fix'],
3 | '*.{json,md,yml,css,ts}': ['prettier --write'],
4 | };
5 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "raw-loader",
3 | "version": "4.0.2",
4 | "description": "A loader for webpack that allows importing files as a String",
5 | "license": "MIT",
6 | "repository": "webpack-contrib/raw-loader",
7 | "author": "Tobias Koppers @sokra",
8 | "homepage": "https://github.com/webpack-contrib/raw-loader",
9 | "bugs": "https://github.com/webpack-contrib/raw-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 | "defaults": "webpack-defaults"
36 | },
37 | "files": [
38 | "dist"
39 | ],
40 | "peerDependencies": {
41 | "webpack": "^4.0.0 || ^5.0.0"
42 | },
43 | "dependencies": {
44 | "loader-utils": "^2.0.0",
45 | "schema-utils": "^3.0.0"
46 | },
47 | "devDependencies": {
48 | "@babel/cli": "^7.11.6",
49 | "@babel/core": "^7.11.6",
50 | "@babel/preset-env": "^7.11.5",
51 | "@commitlint/cli": "^11.0.0",
52 | "@commitlint/config-conventional": "^11.0.0",
53 | "@webpack-contrib/defaults": "^6.3.0",
54 | "@webpack-contrib/eslint-config-webpack": "^3.0.0",
55 | "babel-jest": "^26.5.2",
56 | "cross-env": "^7.0.2",
57 | "del": "^6.0.0",
58 | "del-cli": "^3.0.1",
59 | "eslint": "^7.10.0",
60 | "eslint-config-prettier": "^6.12.0",
61 | "eslint-plugin-import": "^2.22.1",
62 | "eslint-plugin-prettier": "^3.1.4",
63 | "husky": "^4.3.0",
64 | "jest": "^26.5.2",
65 | "lint-staged": "^10.4.0",
66 | "memfs": "^3.2.0",
67 | "npm-run-all": "^4.1.5",
68 | "prettier": "^2.1.2",
69 | "standard-version": "^9.0.0",
70 | "webpack": "^4.44.2"
71 | },
72 | "keywords": [
73 | "webpack"
74 | ]
75 | }
76 |
--------------------------------------------------------------------------------
/src/cjs.js:
--------------------------------------------------------------------------------
1 | const loader = require('./index');
2 |
3 | module.exports = loader.default;
4 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | import { getOptions } from 'loader-utils';
2 | import { validate } from 'schema-utils';
3 |
4 | import schema from './options.json';
5 |
6 | export default function rawLoader(source) {
7 | const options = getOptions(this);
8 |
9 | validate(schema, options, {
10 | name: 'Raw Loader',
11 | baseDataPath: 'options',
12 | });
13 |
14 | const json = JSON.stringify(source)
15 | .replace(/\u2028/g, '\\u2028')
16 | .replace(/\u2029/g, '\\u2029');
17 |
18 | const esModule =
19 | typeof options.esModule !== 'undefined' ? options.esModule : true;
20 |
21 | return `${esModule ? 'export default' : 'module.exports ='} ${json};`;
22 | }
23 |
--------------------------------------------------------------------------------
/src/options.json:
--------------------------------------------------------------------------------
1 | {
2 | "additionalProperties": false,
3 | "properties": {
4 | "esModule": {
5 | "type": "boolean"
6 | }
7 | },
8 | "type": "object"
9 | }
10 |
--------------------------------------------------------------------------------
/test/__snapshots__/esModule-option.test.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`"esModule" option should work with "Boolean" value equal "false": errors 1`] = `Array []`;
4 |
5 | exports[`"esModule" option should work with "Boolean" value equal "false": result 1`] = `
6 | "Где розы — там и тернии —
7 | Таков закон судьбы.
8 |
9 | Николай Алексеевич Некрасов
10 |
11 | Where the roses are - there are thorns -
12 | That is the law of fate.
13 |
14 | Nikolay Alekseevich Nekrasov
15 | "
16 | `;
17 |
18 | exports[`"esModule" option should work with "Boolean" value equal "false": warnings 1`] = `Array []`;
19 |
20 | exports[`"esModule" option should work with "Boolean" value equal "true": errors 1`] = `Array []`;
21 |
22 | exports[`"esModule" option should work with "Boolean" value equal "true": result 1`] = `
23 | "Где розы — там и тернии —
24 | Таков закон судьбы.
25 |
26 | Николай Алексеевич Некрасов
27 |
28 | Where the roses are - there are thorns -
29 | That is the law of fate.
30 |
31 | Nikolay Alekseevich Nekrasov
32 | "
33 | `;
34 |
35 | exports[`"esModule" option should work with "Boolean" value equal "true": warnings 1`] = `Array []`;
36 |
37 | exports[`"esModule" option should work without value: errors 1`] = `Array []`;
38 |
39 | exports[`"esModule" option should work without value: result 1`] = `
40 | "Где розы — там и тернии —
41 | Таков закон судьбы.
42 |
43 | Николай Алексеевич Некрасов
44 |
45 | Where the roses are - there are thorns -
46 | That is the law of fate.
47 |
48 | Nikolay Alekseevich Nekrasov
49 | "
50 | `;
51 |
52 | exports[`"esModule" option should work without value: warnings 1`] = `Array []`;
53 |
--------------------------------------------------------------------------------
/test/__snapshots__/loader.test.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`loader should work with "ModuleConcatenationPlugin" plugin: assets 1`] = `
4 | Array [
5 | "main.bundle.js",
6 | ]
7 | `;
8 |
9 | exports[`loader should work with "ModuleConcatenationPlugin" plugin: errors 1`] = `Array []`;
10 |
11 | exports[`loader should work with "ModuleConcatenationPlugin" plugin: result 1`] = `
12 | "Где розы — там и тернии —
13 | Таков закон судьбы.
14 |
15 | Николай Алексеевич Некрасов
16 |
17 | Where the roses are - there are thorns -
18 | That is the law of fate.
19 |
20 | Nikolay Alekseevich Nekrasov
21 | "
22 | `;
23 |
24 | exports[`loader should work with "ModuleConcatenationPlugin" plugin: warnings 1`] = `Array []`;
25 |
26 | exports[`loader should work with inline loader: assets 1`] = `
27 | Array [
28 | "main.bundle.js",
29 | ]
30 | `;
31 |
32 | exports[`loader should work with inline loader: errors 1`] = `Array []`;
33 |
34 | exports[`loader should work with inline loader: result 1`] = `
35 | "Где розы — там и тернии —
36 | Таков закон судьбы.
37 |
38 | Николай Алексеевич Некрасов
39 |
40 | Where the roses are - there are thorns -
41 | That is the law of fate.
42 |
43 | Nikolay Alekseevich Nekrasov
44 | "
45 | `;
46 |
47 | exports[`loader should work with inline loader: warnings 1`] = `Array []`;
48 |
49 | exports[`loader should work: assets 1`] = `
50 | Array [
51 | "main.bundle.js",
52 | ]
53 | `;
54 |
55 | exports[`loader should work: errors 1`] = `Array []`;
56 |
57 | exports[`loader should work: result 1`] = `
58 | "Где розы — там и тернии —
59 | Таков закон судьбы.
60 |
61 | Николай Алексеевич Некрасов
62 |
63 | Where the roses are - there are thorns -
64 | That is the law of fate.
65 |
66 | Nikolay Alekseevich Nekrasov
67 | "
68 | `;
69 |
70 | exports[`loader should work: warnings 1`] = `Array []`;
71 |
--------------------------------------------------------------------------------
/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 "esModule" option with "true" value 1`] = `
4 | "Invalid options object. Raw Loader has been initialized using an options object that does not match the API schema.
5 | - options.esModule should be a boolean."
6 | `;
7 |
8 | exports[`validate options should throw an error on the "unknown" option with "/test/" value 1`] = `
9 | "Invalid options object. Raw Loader has been initialized using an options object that does not match the API schema.
10 | - options has an unknown property 'unknown'. These properties are valid:
11 | object { esModule? }"
12 | `;
13 |
14 | exports[`validate options should throw an error on the "unknown" option with "[]" value 1`] = `
15 | "Invalid options object. Raw Loader has been initialized using an options object that does not match the API schema.
16 | - options has an unknown property 'unknown'. These properties are valid:
17 | object { esModule? }"
18 | `;
19 |
20 | exports[`validate options should throw an error on the "unknown" option with "{"foo":"bar"}" value 1`] = `
21 | "Invalid options object. Raw Loader has been initialized using an options object that does not match the API schema.
22 | - options has an unknown property 'unknown'. These properties are valid:
23 | object { esModule? }"
24 | `;
25 |
26 | exports[`validate options should throw an error on the "unknown" option with "{}" value 1`] = `
27 | "Invalid options object. Raw Loader has been initialized using an options object that does not match the API schema.
28 | - options has an unknown property 'unknown'. These properties are valid:
29 | object { esModule? }"
30 | `;
31 |
32 | exports[`validate options should throw an error on the "unknown" option with "1" value 1`] = `
33 | "Invalid options object. Raw Loader has been initialized using an options object that does not match the API schema.
34 | - options has an unknown property 'unknown'. These properties are valid:
35 | object { esModule? }"
36 | `;
37 |
38 | exports[`validate options should throw an error on the "unknown" option with "false" value 1`] = `
39 | "Invalid options object. Raw Loader has been initialized using an options object that does not match the API schema.
40 | - options has an unknown property 'unknown'. These properties are valid:
41 | object { esModule? }"
42 | `;
43 |
44 | exports[`validate options should throw an error on the "unknown" option with "test" value 1`] = `
45 | "Invalid options object. Raw Loader has been initialized using an options object that does not match the API schema.
46 | - options has an unknown property 'unknown'. These properties are valid:
47 | object { esModule? }"
48 | `;
49 |
50 | exports[`validate options should throw an error on the "unknown" option with "true" value 1`] = `
51 | "Invalid options object. Raw Loader has been initialized using an options object that does not match the API schema.
52 | - options has an unknown property 'unknown'. These properties are valid:
53 | object { esModule? }"
54 | `;
55 |
--------------------------------------------------------------------------------
/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 | it('should not export "raw" flag', () => {
10 | expect(cjs.raw).toBeUndefined();
11 | });
12 | });
13 |
--------------------------------------------------------------------------------
/test/esModule-option.test.js:
--------------------------------------------------------------------------------
1 | import {
2 | compile,
3 | execute,
4 | getCompiler,
5 | normalizeErrors,
6 | readAsset,
7 | } from './helpers';
8 |
9 | describe('"esModule" option', () => {
10 | it('should work without value', async () => {
11 | const compiler = getCompiler('simple.js');
12 | const stats = await compile(compiler);
13 |
14 | expect(
15 | execute(readAsset('main.bundle.js', compiler, stats))
16 | ).toMatchSnapshot('result');
17 | expect(normalizeErrors(stats.compilation.warnings)).toMatchSnapshot(
18 | 'warnings'
19 | );
20 | expect(normalizeErrors(stats.compilation.errors)).toMatchSnapshot('errors');
21 | });
22 |
23 | it('should work with "Boolean" value equal "true"', async () => {
24 | const compiler = getCompiler('simple.js', {
25 | esModule: true,
26 | });
27 | const stats = await compile(compiler);
28 |
29 | expect(
30 | execute(readAsset('main.bundle.js', compiler, stats))
31 | ).toMatchSnapshot('result');
32 | expect(normalizeErrors(stats.compilation.warnings)).toMatchSnapshot(
33 | 'warnings'
34 | );
35 | expect(normalizeErrors(stats.compilation.errors)).toMatchSnapshot('errors');
36 | });
37 |
38 | it('should work with "Boolean" value equal "false"', async () => {
39 | const compiler = getCompiler('simple.js', {
40 | esModule: false,
41 | });
42 | const stats = await compile(compiler);
43 |
44 | expect(
45 | execute(readAsset('main.bundle.js', compiler, stats))
46 | ).toMatchSnapshot('result');
47 | expect(normalizeErrors(stats.compilation.warnings)).toMatchSnapshot(
48 | 'warnings'
49 | );
50 | expect(normalizeErrors(stats.compilation.errors)).toMatchSnapshot('errors');
51 | });
52 | });
53 |
--------------------------------------------------------------------------------
/test/fixtures/file.txt:
--------------------------------------------------------------------------------
1 | Где розы — там и тернии —
2 | Таков закон судьбы.
3 |
4 | Николай Алексеевич Некрасов
5 |
6 | Where the roses are - there are thorns -
7 | That is the law of fate.
8 |
9 | Nikolay Alekseevich Nekrasov
10 |
--------------------------------------------------------------------------------
/test/fixtures/inline.js:
--------------------------------------------------------------------------------
1 | import inline from '!!../../src/index.js!./file.txt';
2 |
3 | __export__ = inline;
4 |
5 | export default inline;
6 |
--------------------------------------------------------------------------------
/test/fixtures/simple.js:
--------------------------------------------------------------------------------
1 | import txt from './file.txt';
2 |
3 | __export__ = txt;
4 |
5 | export default txt;
6 |
--------------------------------------------------------------------------------
/test/helpers/compile.js:
--------------------------------------------------------------------------------
1 | export default (compiler) => {
2 | return 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 | };
12 |
--------------------------------------------------------------------------------
/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 { createFsFromVolume, Volume } from 'memfs';
5 |
6 | export default (fixture, loaderOptions = {}, config = {}) => {
7 | const fullConfig = {
8 | mode: 'development',
9 | devtool: config.devtool || false,
10 | context: path.resolve(__dirname, '../fixtures'),
11 | entry: path.resolve(__dirname, '../fixtures', fixture),
12 | output: {
13 | path: path.resolve(__dirname, '../outputs'),
14 | filename: '[name].bundle.js',
15 | chunkFilename: '[name].chunk.js',
16 | },
17 | module: {
18 | rules: [
19 | {
20 | test: /\.txt$/i,
21 | rules: [
22 | {
23 | loader: path.resolve(__dirname, '../../src'),
24 | options: loaderOptions || {},
25 | },
26 | ],
27 | },
28 | ],
29 | },
30 | plugins: [],
31 | ...config,
32 | };
33 |
34 | const compiler = webpack(fullConfig);
35 |
36 | if (!config.outputFileSystem) {
37 | const outputFileSystem = createFsFromVolume(new Volume());
38 | // Todo remove when we drop webpack@4 support
39 | outputFileSystem.join = path.join.bind(path);
40 |
41 | compiler.outputFileSystem = outputFileSystem;
42 | }
43 |
44 | return compiler;
45 | };
46 |
--------------------------------------------------------------------------------
/test/helpers/index.js:
--------------------------------------------------------------------------------
1 | import compile from './compile';
2 | import execute from './execute';
3 | import getCompiler from './getCompiler';
4 | import normalizeErrors from './normalizeErrors';
5 | import readAsset from './readAsset';
6 |
7 | export { compile, execute, getCompiler, normalizeErrors, readAsset };
8 |
--------------------------------------------------------------------------------
/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 | return errors.map((error) =>
17 | removeCWD(error.toString().split('\n').slice(0, 2).join('\n'))
18 | );
19 | };
20 |
--------------------------------------------------------------------------------
/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 | let data = '';
7 |
8 | try {
9 | data = usedFs.readFileSync(path.join(outputPath, asset)).toString();
10 | } catch (error) {
11 | data = error.toString();
12 | }
13 |
14 | return data;
15 | };
16 |
--------------------------------------------------------------------------------
/test/loader.test.js:
--------------------------------------------------------------------------------
1 | import {
2 | compile,
3 | execute,
4 | getCompiler,
5 | normalizeErrors,
6 | readAsset,
7 | } from './helpers';
8 |
9 | describe('loader', () => {
10 | it('should work', async () => {
11 | const compiler = getCompiler('simple.js');
12 | const stats = await compile(compiler);
13 |
14 | expect(
15 | execute(readAsset('main.bundle.js', compiler, stats))
16 | ).toMatchSnapshot('result');
17 | expect(Object.keys(stats.compilation.assets)).toMatchSnapshot('assets');
18 | expect(normalizeErrors(stats.compilation.warnings)).toMatchSnapshot(
19 | 'warnings'
20 | );
21 | expect(normalizeErrors(stats.compilation.errors)).toMatchSnapshot('errors');
22 | });
23 |
24 | it('should work with inline loader', async () => {
25 | const compiler = getCompiler('inline.js');
26 | const stats = await compile(compiler);
27 |
28 | expect(
29 | execute(readAsset('main.bundle.js', compiler, stats))
30 | ).toMatchSnapshot('result');
31 | expect(Object.keys(stats.compilation.assets)).toMatchSnapshot('assets');
32 | expect(normalizeErrors(stats.compilation.warnings)).toMatchSnapshot(
33 | 'warnings'
34 | );
35 | expect(normalizeErrors(stats.compilation.errors)).toMatchSnapshot('errors');
36 | });
37 |
38 | it('should work with "ModuleConcatenationPlugin" plugin', async () => {
39 | const compiler = getCompiler(
40 | 'simple.js',
41 | {},
42 | {
43 | mode: 'production',
44 | optimization: {
45 | minimize: false,
46 | },
47 | }
48 | );
49 | const stats = await compile(compiler);
50 |
51 | expect(
52 | execute(readAsset('main.bundle.js', compiler, stats))
53 | ).toMatchSnapshot('result');
54 | expect(Object.keys(stats.compilation.assets)).toMatchSnapshot('assets');
55 | expect(normalizeErrors(stats.compilation.warnings)).toMatchSnapshot(
56 | 'warnings'
57 | );
58 | expect(normalizeErrors(stats.compilation.errors)).toMatchSnapshot('errors');
59 |
60 | if (stats.compilation.modules.size) {
61 | expect(stats.compilation.modules.size).toBe(2);
62 | } else {
63 | expect(stats.compilation.modules.length).toBe(1);
64 | }
65 | });
66 | });
67 |
--------------------------------------------------------------------------------
/test/validate-options.test.js:
--------------------------------------------------------------------------------
1 | import { getCompiler, compile } from './helpers';
2 |
3 | describe('validate options', () => {
4 | const tests = {
5 | esModule: {
6 | success: [true, false],
7 | failure: ['true'],
8 | },
9 | unknown: {
10 | success: [],
11 | failure: [1, true, false, 'test', /test/, [], {}, { foo: 'bar' }],
12 | },
13 | };
14 |
15 | function stringifyValue(value) {
16 | if (
17 | Array.isArray(value) ||
18 | (value && typeof value === 'object' && value.constructor === Object)
19 | ) {
20 | return JSON.stringify(value);
21 | }
22 |
23 | return value;
24 | }
25 |
26 | async function createTestCase(key, value, type) {
27 | it(`should ${
28 | type === 'success' ? 'successfully validate' : 'throw an error on'
29 | } the "${key}" option with "${stringifyValue(value)}" value`, async () => {
30 | const compiler = getCompiler('simple.js', { [key]: value });
31 |
32 | let stats;
33 |
34 | try {
35 | stats = await compile(compiler);
36 | } finally {
37 | if (type === 'success') {
38 | expect(stats.hasErrors()).toBe(false);
39 | } else if (type === 'failure') {
40 | const {
41 | compilation: { errors },
42 | } = stats;
43 |
44 | expect(errors).toHaveLength(1);
45 | expect(() => {
46 | throw new Error(errors[0].error.message);
47 | }).toThrowErrorMatchingSnapshot();
48 | }
49 | }
50 | });
51 | }
52 |
53 | for (const [key, values] of Object.entries(tests)) {
54 | for (const type of Object.keys(values)) {
55 | for (const value of values[type]) {
56 | createTestCase(key, value, type);
57 | }
58 | }
59 | }
60 | });
61 |
--------------------------------------------------------------------------------