Skip to content
This repository was archived by the owner on Mar 17, 2021. It is now read-only.

Commit 5ec82d6

Browse files
authoredNov 25, 2019
refactor: next (#88)
1 parent d231710 commit 5ec82d6

27 files changed

+2775
-2006
lines changed
 

‎.editorconfig

-1
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,4 @@ insert_final_newline = true
99
trim_trailing_whitespace = true
1010

1111
[*.md]
12-
insert_final_newline = true
1312
trim_trailing_whitespace = false

‎README.md

+35-1
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,40 @@ $ webpack --module-bind 'txt=raw-loader'
5959

6060
And run `webpack` via your preferred method.
6161

62+
## Options
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+
6296
## Examples
6397

6498
### Inline
@@ -70,7 +104,7 @@ import txt from 'raw-loader!./file.txt';
70104
Beware, if you already define loader(s) for extension(s) in `webpack.config.js` you should use:
71105

72106
```js
73-
import css from '!!raw-loader!./file.css'; // Adding `!!` to a request will disable all loaders specified in the configuration
107+
import css from '!!raw-loader!./file.txt'; // Adding `!!` to a request will disable all loaders specified in the configuration
74108
```
75109

76110
## Contributing

‎azure-pipelines.yml

+42-34
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,13 @@ trigger:
22
- master
33
- next
44

5+
variables:
6+
npm_config_cache: $(Pipeline.Workspace)/.npm
7+
58
jobs:
69
- job: Lint
710
pool:
8-
vmImage: ubuntu-16.04
11+
vmImage: ubuntu-latest
912
steps:
1013
- task: NodeTool@0
1114
inputs:
@@ -20,10 +23,12 @@ jobs:
2023
node -v
2124
npm -v
2225
displayName: 'Print versions'
23-
- task: Npm@1
26+
- task: CacheBeta@1
2427
inputs:
25-
command: custom
26-
customCommand: ci
28+
key: npm | $(Agent.OS) | package-lock.json
29+
path: $(npm_config_cache)
30+
displayName: 'Cache npm'
31+
- script: npm ci
2732
displayName: 'Install dependencies'
2833
- script: npm run lint
2934
displayName: 'Run lint'
@@ -34,23 +39,22 @@ jobs:
3439

3540
- job: Linux
3641
pool:
37-
vmImage: ubuntu-16.04
42+
vmImage: ubuntu-latest
3843
strategy:
3944
maxParallel: 4
4045
matrix:
46+
node-13:
47+
node_version: ^13.0.0
48+
webpack_version: latest
4149
node-12:
4250
node_version: ^12.0.0
4351
webpack_version: latest
4452
node-10:
4553
node_version: ^10.13.0
4654
webpack_version: latest
47-
node-8:
48-
node_version: ^8.9.0
49-
webpack_version: latest
50-
node-8-canary:
51-
node_version: ^8.9.0
55+
node-10-canary:
56+
node_version: ^10.13.0
5257
webpack_version: next
53-
continue_on_error: true
5458
steps:
5559
- task: NodeTool@0
5660
inputs:
@@ -65,10 +69,12 @@ jobs:
6569
node -v
6670
npm -v
6771
displayName: 'Print versions'
68-
- task: Npm@1
72+
- task: CacheBeta@1
6973
inputs:
70-
command: custom
71-
customCommand: ci
74+
key: npm | $(Agent.OS) | package-lock.json
75+
path: $(npm_config_cache)
76+
displayName: 'Cache npm'
77+
- script: npm ci
7278
displayName: 'Install dependencies'
7379
- script: npm i webpack@$(webpack_version)
7480
displayName: 'Install "webpack@$(webpack_version)"'
@@ -86,23 +92,22 @@ jobs:
8692

8793
- job: macOS
8894
pool:
89-
vmImage: macOS-10.14
95+
vmImage: macOS-latest
9096
strategy:
9197
maxParallel: 4
9298
matrix:
99+
node-13:
100+
node_version: ^13.0.0
101+
webpack_version: latest
93102
node-12:
94103
node_version: ^12.0.0
95104
webpack_version: latest
96105
node-10:
97106
node_version: ^10.13.0
98107
webpack_version: latest
99-
node-8:
100-
node_version: ^8.9.0
101-
webpack_version: latest
102-
node-8-canary:
103-
node_version: ^8.9.0
108+
node-10-canary:
109+
node_version: ^10.13.0
104110
webpack_version: next
105-
continue_on_error: true
106111
steps:
107112
- task: NodeTool@0
108113
inputs:
@@ -117,10 +122,12 @@ jobs:
117122
node -v
118123
npm -v
119124
displayName: 'Print versions'
120-
- task: Npm@1
125+
- task: CacheBeta@1
121126
inputs:
122-
command: custom
123-
customCommand: ci
127+
key: npm | $(Agent.OS) | package-lock.json
128+
path: $(npm_config_cache)
129+
displayName: 'Cache npm'
130+
- script: npm ci
124131
displayName: 'Install dependencies'
125132
- script: npm i webpack@$(webpack_version)
126133
displayName: 'Install "webpack@$(webpack_version)"'
@@ -138,23 +145,22 @@ jobs:
138145

139146
- job: Windows
140147
pool:
141-
vmImage: windows-2019
148+
vmImage: windows-latest
142149
strategy:
143150
maxParallel: 4
144151
matrix:
152+
node-13:
153+
node_version: ^13.0.0
154+
webpack_version: latest
145155
node-12:
146156
node_version: ^12.0.0
147157
webpack_version: latest
148158
node-10:
149159
node_version: ^10.13.0
150160
webpack_version: latest
151-
node-8:
152-
node_version: ^8.9.0
153-
webpack_version: latest
154-
node-8-canary:
155-
node_version: ^8.9.0
161+
node-10-canary:
162+
node_version: ^10.13.0
156163
webpack_version: next
157-
continue_on_error: true
158164
steps:
159165
- script: 'git config --global core.autocrlf input'
160166
displayName: 'Config git core.autocrlf'
@@ -172,10 +178,12 @@ jobs:
172178
node -v
173179
npm -v
174180
displayName: 'Print versions'
175-
- task: Npm@1
181+
- task: CacheBeta@1
176182
inputs:
177-
command: custom
178-
customCommand: ci
183+
key: npm | $(Agent.OS) | package-lock.json
184+
path: $(npm_config_cache)
185+
displayName: 'Cache npm'
186+
- script: npm ci
179187
displayName: 'Install dependencies'
180188
- script: npm i webpack@$(webpack_version)
181189
displayName: 'Install "webpack@$(webpack_version)"'

‎babel.config.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ module.exports = (api) => {
1010
'@babel/preset-env',
1111
{
1212
targets: {
13-
node: '8.9.0',
13+
node: '10.13.0',
1414
},
1515
},
1616
],

‎lint-staged.config.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
module.exports = {
22
'*.js': ['prettier --write', 'eslint --fix', 'git add'],
3-
'*.{json,md,yml,css}': ['prettier --write', 'git add'],
3+
'*.{json,md,yml,css,ts}': ['prettier --write', 'git add'],
44
};

‎package-lock.json

+2,173-1,805
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json

+41-37
Original file line numberDiff line numberDiff line change
@@ -7,65 +7,69 @@
77
"author": "Tobias Koppers @sokra",
88
"homepage": "https://github.com/webpack-contrib/raw-loader",
99
"bugs": "https://github.com/webpack-contrib/raw-loader/issues",
10+
"funding": {
11+
"type": "opencollective",
12+
"url": "https://opencollective.com/webpack"
13+
},
1014
"main": "dist/cjs.js",
1115
"engines": {
12-
"node": ">= 8.9.0"
16+
"node": ">= 10.13.0"
1317
},
1418
"scripts": {
1519
"start": "npm run build -- -w",
16-
"prebuild": "npm run clean",
17-
"build": "cross-env NODE_ENV=production babel src -d dist --ignore \"src/**/*.test.js\" --copy-files",
1820
"clean": "del-cli dist",
21+
"prebuild": "npm run clean",
22+
"build": "cross-env NODE_ENV=production babel src -d dist --copy-files",
1923
"commitlint": "commitlint --from=master",
20-
"lint:prettier": "prettier \"{**/*,*}.{js,json,md,yml,css}\" --list-different",
21-
"lint:js": "eslint --cache src test",
22-
"lint": "npm-run-all -l -p \"lint:**\"",
23-
"prepare": "npm run build",
24-
"release": "standard-version",
2524
"security": "npm audit",
25+
"lint:prettier": "prettier \"{**/*,*}.{js,json,md,yml,css,ts}\" --list-different",
26+
"lint:js": "eslint --cache .",
27+
"lint": "npm-run-all -l -p \"lint:**\"",
2628
"test:only": "cross-env NODE_ENV=test jest",
27-
"test:watch": "cross-env NODE_ENV=test jest --watch",
28-
"test:coverage": "cross-env NODE_ENV=test jest --collectCoverageFrom=\"src/**/*.js\" --coverage",
29+
"test:watch": "npm run test:only -- --watch",
30+
"test:coverage": "npm run test:only -- --collectCoverageFrom=\"src/**/*.js\" --coverage",
2931
"pretest": "npm run lint",
30-
"test": "cross-env NODE_ENV=test npm run test:coverage",
32+
"test": "npm run test:coverage",
33+
"prepare": "npm run build",
34+
"release": "standard-version",
3135
"defaults": "webpack-defaults"
3236
},
3337
"files": [
34-
"dist/"
38+
"dist"
3539
],
3640
"peerDependencies": {
37-
"webpack": "^4.3.0"
41+
"webpack": "^4.0.0 || ^5.0.0"
3842
},
3943
"dependencies": {
40-
"loader-utils": "^1.1.0",
41-
"schema-utils": "^2.0.1"
44+
"loader-utils": "^1.2.3",
45+
"schema-utils": "^2.5.0"
4246
},
4347
"devDependencies": {
44-
"@babel/cli": "^7.5.5",
45-
"@babel/core": "^7.5.5",
46-
"@babel/preset-env": "^7.5.5",
47-
"@commitlint/cli": "^8.1.0",
48-
"@commitlint/config-conventional": "^8.1.0",
49-
"@webpack-contrib/defaults": "^5.0.2",
48+
"@babel/cli": "^7.7.4",
49+
"@babel/core": "^7.7.4",
50+
"@babel/preset-env": "^7.7.4",
51+
"@commitlint/cli": "^8.2.0",
52+
"@commitlint/config-conventional": "^8.2.0",
53+
"@webpack-contrib/defaults": "^6.2.0",
5054
"@webpack-contrib/eslint-config-webpack": "^3.0.0",
51-
"babel-jest": "^24.8.0",
55+
"babel-jest": "^24.9.0",
5256
"commitlint-azure-pipelines-cli": "^1.0.2",
53-
"cross-env": "^5.2.0",
54-
"del": "^5.0.0",
55-
"del-cli": "^2.0.0",
56-
"eslint": "^6.0.1",
57-
"eslint-config-prettier": "^6.0.0",
58-
"eslint-plugin-import": "^2.18.0",
59-
"eslint-plugin-prettier": "^3.1.0",
60-
"husky": "^3.0.0",
61-
"jest": "^24.8.0",
62-
"jest-junit": "^6.4.0",
63-
"lint-staged": "^9.2.0",
64-
"memory-fs": "^0.4.1",
57+
"cross-env": "^6.0.3",
58+
"del": "^5.1.0",
59+
"del-cli": "^3.0.0",
60+
"eslint": "^6.7.1",
61+
"eslint-config-prettier": "^6.7.0",
62+
"eslint-plugin-import": "^2.18.2",
63+
"eslint-plugin-prettier": "^3.1.1",
64+
"husky": "^3.1.0",
65+
"jest": "^24.9.0",
66+
"jest-junit": "^9.0.0",
67+
"lint-staged": "^9.4.3",
68+
"memfs": "^2.16.1",
6569
"npm-run-all": "^4.1.5",
66-
"prettier": "^1.18.2",
67-
"standard-version": "^6.0.1",
68-
"webpack": "^4.36.1"
70+
"prettier": "^1.19.1",
71+
"standard-version": "^7.0.1",
72+
"webpack": "^4.41.2"
6973
},
7074
"keywords": [
7175
"webpack"

‎src/index.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,8 @@ export default function rawLoader(source) {
1515
.replace(/\u2028/g, '\\u2028')
1616
.replace(/\u2029/g, '\\u2029');
1717

18-
return `export default ${json}`;
18+
const esModule =
19+
typeof options.esModule !== 'undefined' ? options.esModule : true;
20+
21+
return `${esModule ? 'export default' : 'module.exports ='} ${json};`;
1922
}

‎src/options.json

+5-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
{
22
"additionalProperties": false,
3-
"properties": {},
3+
"properties": {
4+
"esModule": {
5+
"type": "boolean"
6+
}
7+
},
48
"type": "object"
59
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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 []`;
+64-5
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,70 @@
11
// Jest Snapshot v1, https://goo.gl/fbAQLP
22

3-
exports[`loader should works: errors 1`] = `Array []`;
3+
exports[`loader should work with "ModuleConcatenationPlugin" plugin: assets 1`] = `
4+
Array [
5+
"main.bundle.js",
6+
]
7+
`;
48

5-
exports[`loader should works: file 1`] = `"export default \\"Где розы — там и тернии —\\\\nТаков закон судьбы.\\\\n\\\\nНиколай Алексеевич Некрасов\\\\n\\\\nWhere the roses are - there are thorns -\\\\nThat is the law of fate.\\\\n\\\\nNikolay Alekseevich Nekrasov\\\\n\\""`;
9+
exports[`loader should work with "ModuleConcatenationPlugin" plugin: errors 1`] = `Array []`;
610

7-
exports[`loader should works: inline 1`] = `"export default \\"Где розы — там и тернии —\\\\nТаков закон судьбы.\\\\n\\\\nНиколай Алексеевич Некрасов\\\\n\\\\nWhere the roses are - there are thorns -\\\\nThat is the law of fate.\\\\n\\\\nNikolay Alekseevich Nekrasov\\\\n\\""`;
11+
exports[`loader should work with "ModuleConcatenationPlugin" plugin: result 1`] = `
12+
"Где розы — там и тернии —
13+
Таков закон судьбы.
814
9-
exports[`loader should works: separator 1`] = `"export default \\"Word\\\\u2028Word\\\\u2029Word\\\\n\\""`;
15+
Николай Алексеевич Некрасов
1016
11-
exports[`loader should works: warnings 1`] = `Array []`;
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 []`;
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,54 @@
11
// Jest Snapshot v1, https://goo.gl/fbAQLP
22

3-
exports[`validate options 1`] = `
3+
exports[`validate options should throw an error on the "esModule" option with "true" value 1`] = `
4+
"Invalid options object. Raw Loader has been initialised 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 initialised 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 initialised 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 initialised 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 initialised 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 initialised 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 initialised 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 initialised 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`] = `
451
"Invalid options object. Raw Loader has been initialised using an options object that does not match the API schema.
552
- options has an unknown property 'unknown'. These properties are valid:
6-
object {}"
53+
object { esModule? }"
754
`;

‎test/cjs.test.js

+4
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,8 @@ describe('cjs', () => {
55
it('should exported', () => {
66
expect(cjs).toEqual(src);
77
});
8+
9+
it('should not export "raw" flag', () => {
10+
expect(cjs.raw).toBeUndefined();
11+
});
812
});

‎test/esModule-option.test.js

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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+
});

‎test/fixtures/basic.js

-7
This file was deleted.

‎test/fixtures/inline.js

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import inline from '!!../../src/index.js!./file.txt';
2+
3+
__export__ = inline;
4+
5+
export default inline;

‎test/fixtures/separator.txt

-1
This file was deleted.

‎test/fixtures/simple.js

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import txt from './file.txt';
2+
3+
__export__ = txt;
4+
5+
export default txt;

‎test/helpers.js

-84
This file was deleted.

‎test/helpers/compile.js

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
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+
};

‎test/helpers/execute.js

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
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+
};

‎test/helpers/getCompiler.js

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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+
};

‎test/helpers/index.js

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
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 };

‎test/helpers/normalizeErrors.js

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
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(
18+
error
19+
.toString()
20+
.split('\n')
21+
.slice(0, 2)
22+
.join('\n')
23+
)
24+
);
25+
};

‎test/helpers/readAsset.js

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
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+
};

‎test/loader.test.js

+60-10
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,66 @@
1-
import { webpack } from './helpers';
1+
import {
2+
compile,
3+
execute,
4+
getCompiler,
5+
normalizeErrors,
6+
readAsset,
7+
} from './helpers';
28

39
describe('loader', () => {
4-
it('should works', async () => {
5-
const stats = await webpack('basic.js');
6-
const { modules } = stats.toJson();
7-
const [inline, , file, separator] = modules;
10+
it('should work', async () => {
11+
const compiler = getCompiler('simple.js');
12+
const stats = await compile(compiler);
813

9-
expect(inline.source).toMatchSnapshot('inline');
10-
expect(file.source).toMatchSnapshot('file');
11-
expect(separator.source).toMatchSnapshot('separator');
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');
1259

13-
expect(stats.compilation.warnings).toMatchSnapshot('warnings');
14-
expect(stats.compilation.errors).toMatchSnapshot('errors');
60+
if (stats.compilation.modules.size) {
61+
expect(stats.compilation.modules.size).toBe(1);
62+
} else {
63+
expect(stats.compilation.modules.length).toBe(1);
64+
}
1565
});
1666
});

‎test/validate-options.test.js

+57-15
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,60 @@
1-
import loader from '../src';
2-
3-
it('validate options', () => {
4-
const validate = (options) =>
5-
loader.call(
6-
Object.assign(
7-
{},
8-
{
9-
query: options,
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();
1048
}
11-
),
12-
'Text'
13-
);
49+
}
50+
});
51+
}
1452

15-
expect(() => validate({})).not.toThrow();
16-
expect(() => validate(true)).not.toThrow();
17-
expect(() => validate({ unknown: true })).toThrowErrorMatchingSnapshot();
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+
}
1860
});

0 commit comments

Comments
 (0)
This repository has been archived.