Skip to content

Commit 53f58a9

Browse files
authored
Merge pull request #3 from morganney/develop
fix: breaking changes in 1.3.0, regex for comment detection
2 parents 8d60a6d + 87d5a0f commit 53f58a9

File tree

11 files changed

+109
-49
lines changed

11 files changed

+109
-49
lines changed

README.md

Lines changed: 37 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# [`magic-comments-loader`](https://www.npmjs.com/package/magic-comments-loader)
22

3-
Adds [magic coments](https://webpack.js.org/api/module-methods/#magic-comments) to your dynamic `import()` statements.
3+
Keep your source code clean, add [magic coments](https://webpack.js.org/api/module-methods/#magic-comments) to your dynamic `import()` statements at build time.
44

55
NOTE: **This loader ignores dynamic imports that already include comments of any kind**.
66

@@ -16,6 +16,26 @@ Magic comments supported:
1616

1717
First `npm install magic-comments-loader`.
1818

19+
Try *not* to have dynamic `import()` statements behind [comments](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#comments). **It is better to remove unused code in production**.
20+
If you must, e.g. your comment is referencing usage of dynamic imports, then these styles are ok:
21+
22+
```js
23+
// import('some-ignored-module')
24+
/* Some comment about a dynamic import('module') */
25+
```
26+
27+
If you must have a multiline comment then this style is ok (only one `import()` per comment line preceded by an asterisk):
28+
29+
```js
30+
/**
31+
* Comment about import('module/one')
32+
* Comment about import('module/two')
33+
* import('module/three'), etc.
34+
*/
35+
```
36+
37+
This module uses a [RegExp](https://github.com/morganney/magic-comments-loader/blob/master/src/loader.js#L8) not a parser. If you would like to add better support for ignoring `import()` behind multiline comments please open a pull request. See some more [examples on regexr](https://regexr.com/65fg0).
38+
1939
### Configuration
2040

2141
Add this inside your `webpack.config.js`.
@@ -52,8 +72,11 @@ module: {
5272
webpackChunkName: true,
5373
webpackMode: 'lazy',
5474
webpackIgnore: 'src/ignore/**/*.js',
55-
webpackPreload: ['src/preload/**/*.js', '!src/preload/skip/**/*.js'],
5675
webpackPrefetch: 'src/prefetch/**/*.js'
76+
webpackPreload: [
77+
'src/preload/**/*.js',
78+
'!src/preload/skip/**/*.js'
79+
]
5780
}
5881
}
5982
}
@@ -107,19 +130,19 @@ You can also override the configuration passed in the `config` key by using `ove
107130
```js
108131
overrides: [
109132
{
110-
// Can be an array of globs too
111-
files: 'src/**/*.js',
133+
files: ['src/**/*.js'],
112134
config: {
113135
active: true,
114-
exports: ['foo', 'bar']
115-
// Etc.
136+
mode: (modulePath, importPath) => {
137+
if (/eager/.test(importPath)) {
138+
return 'eager'
139+
}
140+
}
116141
}
117142
}
118143
]
119144
```
120145

121-
**The `config.match` in an override is ignored. You can only have one, top-level `config.match`**.
122-
123146
Here's a more complete example using `config` and `overrides` to customize how comments are applied:
124147

125148
```js
@@ -151,7 +174,10 @@ module: {
151174
}
152175
]
153176
},
154-
webpackPrefetch: ['src/prefetch/**/*.js', '!src/prefetch/skip/**/*.js'],
177+
webpackPrefetch: [
178+
'src/prefetch/**/*.js',
179+
'!src/prefetch/skip/**/*.js'
180+
],
155181
webpackMode: {
156182
config: {
157183
mode: 'lazy'
@@ -210,7 +236,7 @@ const dynamicModule = await import(/* webpackChunkName: "path-to-module", webpac
210236

211237
## Options
212238

213-
These are the options that can be configured under the loader `options`. When using comments with a [`config`](#with-config-options) key, you may also specify [`overrides`](#overrides)(`config.match` is ignored inside overrides).
239+
These are the options that can be configured under the loader `options`. When using comments with a [`config`](#with-config-options) key, you may also specify [`overrides`](#overrides).
214240

215241
* `verbose`: Boolean. Prints console statements of the module filepath and updated `import()` during the webpack build. Useful for debugging your custom configurations.
216242
* `match`: `String(module|import)`. Sets how globs are matched, either the module file path or the `import()` path. Defaults to `'module'`.
@@ -245,7 +271,7 @@ These are the options that can be configured under the loader `options`. When us
245271
* `String(lazy|lazy-once|eager|weak)`: Adds the comment to **all** dynamic imports using the provided value.
246272
* `Function`: `(modulePath, importPath) => String(lazy|lazy-once|eager|weak)`. Return falsy value to skip.
247273
* `config.active`: Boolean | `(modulePath, importPath) => Boolean`. Returning `false` does not add the comment.
248-
* `config.mode`: `(modulePath, importPath) => String(lazy|lazy-once|eager|weak)`. Return falsy value to skip.
274+
* `config.mode`: `String(lazy|lazy-once|eager|weak)` | `(modulePath, importPath) => String(lazy|lazy-once|eager|weak)`. Return falsy value to skip.
249275
* `webpackExports`
250276
* `Function`: `(modulePath, importPath) => [String(<module names|default>)]`. Return falsy value to skip.
251277
* `config.active`: Boolean | `(modulePath, importPath) => Boolean`. Returning `false` does not add the comment.

__tests__/webpackChunkName.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ describe('webpackChunkName', () => {
99
expect(webpackChunkName(testPath, testImportPath, true)).toEqual(
1010
'webpackChunkName: "some-import-path"'
1111
)
12+
expect(webpackChunkName(testPath, testImportPath, false)).toEqual('')
1213
expect(webpackChunkName(testPath, testImportPath, 'some/**/*.js')).toEqual(
1314
'webpackChunkName: "some-import-path"'
1415
)

__tests__/webpackExports.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ describe('webpackExports', () => {
1212
expect(comment).toEqual('webpackExports: ["mock"]')
1313
expect(exports).toHaveBeenCalledWith('some/test/module.js', './some/import/path')
1414
expect(webpackExports(testPath, testImportPath, true)).toEqual('')
15+
expect(webpackExports(testPath, testImportPath, false)).toEqual('')
1516
expect(
1617
webpackExports(testPath, testImportPath, {
1718
config: { active: () => true, exports: () => ['one', 'two'] }

__tests__/webpackMode.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,22 @@ describe('webpackMode', () => {
66
const testImportPath = './some/import/path'
77

88
expect(webpackMode(testPath, testImportPath, true)).toEqual('webpackMode: "lazy"')
9+
expect(webpackMode(testPath, testImportPath, false)).toEqual('')
910
expect(webpackMode(testPath, testImportPath, 'eager')).toEqual('webpackMode: "eager"')
1011
expect(webpackMode(testPath, testImportPath, () => 'lazy-once')).toEqual(
1112
'webpackMode: "lazy-once"'
1213
)
1314
expect(webpackMode(testPath, testImportPath, () => 'invalid')).toEqual('')
1415
expect(
1516
webpackMode(testPath, testImportPath, {
16-
config: { mode: () => 'lazy', active: () => true }
17+
config: { mode: 'lazy', active: () => true }
1718
})
1819
).toEqual('webpackMode: "lazy"')
20+
expect(
21+
webpackMode(testPath, testImportPath, {
22+
config: { mode: () => 'weak' }
23+
})
24+
).toEqual('webpackMode: "weak"')
1925
expect(
2026
webpackMode(testPath, testImportPath, {
2127
config: { mode: 'weak' },

__tests__/webpackPrefetch.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ describe('webpackPrefetch', () => {
88
expect(webpackPrefetch(testPath, testImportPath, true)).toEqual(
99
'webpackPrefetch: true'
1010
)
11+
expect(webpackPrefetch(testPath, testImportPath, false)).toEqual('')
1112
expect(webpackPrefetch(testPath, testImportPath, 'some/**/*.js')).toEqual(
1213
'webpackPrefetch: true'
1314
)

package-lock.json

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "magic-comments-loader",
3-
"version": "1.3.0",
3+
"version": "1.3.1",
44
"description": "Add webpack magic comments to your dynamic imports during build time",
55
"main": "dist",
66
"type": "module",
@@ -17,6 +17,7 @@
1717
"scripts": {
1818
"prepack": "node --experimental-json-modules ./prepack.js",
1919
"lint": "eslint . src __tests__ --ext .js,.cjs",
20+
"lint:fix": "npm run lint -- --fix",
2021
"test": "node --experimental-vm-modules ./node_modules/.bin/jest"
2122
},
2223
"keywords": [

src/booleanComment.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,13 @@ const getConfig = (
4444
return defaultConfig
4545
}
4646

47+
if (value === false) {
48+
return {
49+
...defaultConfig,
50+
active: false
51+
}
52+
}
53+
4754
if (Array.isArray(value) || typeof value === 'string') {
4855
return {
4956
...defaultConfig,

src/comment.js

Lines changed: 26 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,34 @@
11
import { commentFor } from './strategy.js'
22

3-
const getCommenter = (filepath, options) => (rgxMatch, capturedImportPath) => {
4-
const importPath = capturedImportPath.trim()
5-
const bareImportPath = importPath.replace(/['"`]/g, '')
6-
const { verbose, match, ...magicCommentOptions } = options
7-
const magicComment = Object.keys(magicCommentOptions)
8-
.map(key => {
9-
const option = magicCommentOptions[key]
3+
const getCommenter =
4+
(filepath, options, logger = console) =>
5+
(rgxMatch, capturedImportPath) => {
6+
const importPath = capturedImportPath.trim()
7+
const bareImportPath = importPath.replace(/['"`]/g, '')
8+
const { verbose, match, ...magicCommentOptions } = options
9+
const magicComment = Object.keys(magicCommentOptions)
10+
.map(key => {
11+
const option = magicCommentOptions[key]
1012

11-
if (option) {
12-
return commentFor[key](filepath, bareImportPath, option, match)
13-
}
13+
if (option) {
14+
return commentFor[key](filepath, bareImportPath, option, match)
15+
}
1416

15-
return null
16-
})
17-
.filter(comment => comment)
18-
const magicImport = rgxMatch.replace(
19-
capturedImportPath,
20-
magicComment.length > 0
21-
? `/* ${magicComment.join(', ')} */ ${importPath}`
22-
: `${importPath}`
23-
)
17+
return null
18+
})
19+
.filter(comment => comment)
20+
const magicImport = rgxMatch.replace(
21+
capturedImportPath,
22+
magicComment.length > 0
23+
? `/* ${magicComment.join(', ')} */ ${importPath}`
24+
: `${importPath}`
25+
)
2426

25-
if (verbose) {
26-
// eslint-disable-next-line no-console
27-
console.log('\x1b[32m%s\x1b[0m', '[MCL]', `${filepath} : ${magicImport}`)
28-
}
27+
if (verbose) {
28+
logger.info('[MCL]', `${filepath} : ${magicImport}`)
29+
}
2930

30-
return magicImport
31-
}
31+
return magicImport
32+
}
3233

3334
export { getCommenter }

src/loader.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,11 @@ import { schema } from './schema.js'
55
import { getCommenter } from './comment.js'
66

77
const dynamicImportsWithoutComments =
8-
/(?<!\w|\*[\s\w]*?|\/\/\s*)import\s*\((?!\s*\/\*)(?<path>\s*?['"`].+['"`]\s*)\)/g
8+
/(?<![\w.]|#!|\*[\s\w]*?|\/\/\s*)import\s*\((?!\s*\/\*)(?<path>\s*?['"`][^)]+['"`]\s*)\)(?![\s]*?\*\/)/g
99
const loader = function (source, map, meta) {
1010
const options = getOptions(this)
1111
const optionKeys = Object.keys(options)
12+
const logger = this.getLogger('MCL')
1213

1314
validate(schema, options, {
1415
name: 'magic-comments-loader'
@@ -17,7 +18,8 @@ const loader = function (source, map, meta) {
1718
const filepath = this.utils.contextify(this.rootContext, this.resourcePath)
1819
const magicComments = getCommenter(
1920
filepath.replace(/^\.\/?/, ''),
20-
optionKeys.length > 0 ? options : { match: 'module', webpackChunkName: true }
21+
optionKeys.length > 0 ? options : { match: 'module', webpackChunkName: true },
22+
logger
2123
)
2224

2325
this.callback(

0 commit comments

Comments
 (0)