Allow ModuleScopePlugin accecpts an array as its appSrc (#4138)

* allow appSrc accepting an array

* fixture of finding all appSrcs logic

* update docs on ModuleScopePlugin accepts an array for appSrc

* minor typo fix in docs: change directory to directories.
This commit is contained in:
froyog
2018-03-23 20:28:41 +08:00
committed by Andreas Cederström
parent 058d03f8f8
commit 1922f4d4d8
2 changed files with 19 additions and 11 deletions

View File

@@ -12,12 +12,12 @@ const path = require('path');
class ModuleScopePlugin {
constructor(appSrc, allowedFiles = []) {
this.appSrc = appSrc;
this.appSrcs = Array.isArray(appSrc) ? appSrc : [appSrc];
this.allowedFiles = new Set(allowedFiles);
}
apply(resolver) {
const { appSrc } = this;
const { appSrcs } = this;
resolver.plugin('file', (request, callback) => {
// Unknown issuer, probably webpack internals
if (!request.context.issuer) {
@@ -34,9 +34,13 @@ class ModuleScopePlugin {
}
// Resolve the issuer from our appSrc and make sure it's one of our files
// Maybe an indexOf === 0 would be better?
const relative = path.relative(appSrc, request.context.issuer);
// If it's not in src/ or a subdirectory, not our request!
if (relative.startsWith('../') || relative.startsWith('..\\')) {
if (
appSrcs.every(appSrc => {
const relative = path.relative(appSrc, request.context.issuer);
// If it's not in one of our app src or a subdirectory, not our request!
return relative.startsWith('../') || relative.startsWith('..\\');
})
) {
return callback();
}
const requestFullPath = path.resolve(
@@ -47,11 +51,15 @@ class ModuleScopePlugin {
return callback();
}
// Find path from src to the requested file
// Error if in a parent directory of src/
const requestRelative = path.relative(appSrc, requestFullPath);
// Error if in a parent directory of all given appSrcs
if (
requestRelative.startsWith('../') ||
requestRelative.startsWith('..\\')
appSrcs.every(appSrc => {
const requestRelative = path.relative(appSrc, requestFullPath);
return (
requestRelative.startsWith('../') ||
requestRelative.startsWith('..\\')
);
})
) {
callback(
new Error(

View File

@@ -57,9 +57,9 @@ module.exports = {
```
#### `new ModuleScopePlugin(appSrc: string, allowedFiles?: string[])`
#### `new ModuleScopePlugin(appSrc: string | string[], allowedFiles?: string[])`
This Webpack plugin ensures that relative imports from app's source directory don't reach outside of it.
This Webpack plugin ensures that relative imports from app's source directories don't reach outside of it.
```js
var path = require('path');