|
| 1 | +/** |
| 2 | + * Copyright (c) 2015-present, Facebook, Inc. |
| 3 | + * All rights reserved. |
| 4 | + * |
| 5 | + * This source code is licensed under the BSD-style license found in the |
| 6 | + * LICENSE file in the root directory of this source tree. An additional grant |
| 7 | + * of patent rights can be found in the PATENTS file in the same directory. |
| 8 | + */ |
| 9 | + |
| 10 | +'use strict'; |
| 11 | + |
| 12 | +const chalk = require('chalk'); |
| 13 | +const path = require('path'); |
| 14 | + |
| 15 | +class ModuleScopePlugin { |
| 16 | + constructor(appSrc) { |
| 17 | + this.appSrc = appSrc; |
| 18 | + } |
| 19 | + |
| 20 | + apply(resolver) { |
| 21 | + const { appSrc } = this; |
| 22 | + resolver.plugin('file', (request, callback) => { |
| 23 | + // Unknown issuer, probably webpack internals |
| 24 | + if (!request.context.issuer) { |
| 25 | + return callback(); |
| 26 | + } |
| 27 | + if ( |
| 28 | + // If this resolves to a node_module, we don't care what happens next |
| 29 | + request.descriptionFileRoot.indexOf('/node_modules/') !== -1 || |
| 30 | + request.descriptionFileRoot.indexOf('\\node_modules\\') !== -1 || |
| 31 | + // Make sure this request was manual |
| 32 | + !request.__innerRequest_request |
| 33 | + ) { |
| 34 | + return callback(); |
| 35 | + } |
| 36 | + // Resolve the issuer from our appSrc and make sure it's one of our files |
| 37 | + // Maybe an indexOf === 0 would be better? |
| 38 | + const relative = path.relative(appSrc, request.context.issuer); |
| 39 | + // If it's not in src/ or a subdirectory, not our request! |
| 40 | + if (relative[0] === '.') { |
| 41 | + return callback(); |
| 42 | + } |
| 43 | + // Find path from src to the requested file |
| 44 | + const requestRelative = path.relative( |
| 45 | + appSrc, |
| 46 | + path.resolve( |
| 47 | + path.dirname(request.context.issuer), |
| 48 | + request.__innerRequest_request |
| 49 | + ) |
| 50 | + ); |
| 51 | + // Error if in a parent directory of src/ |
| 52 | + if (requestRelative[0] === '.') { |
| 53 | + callback( |
| 54 | + new Error( |
| 55 | + `You attempted to import ${chalk.cyan(request.__innerRequest_request)} which falls outside of the project ${chalk.cyan('src/')} directory. ` + |
| 56 | + `Relative imports outside of ${chalk.cyan('src/')} are not supported. ` + |
| 57 | + `You can either move it inside ${chalk.cyan('src/')}, or add a symlink to it from project's ${chalk.cyan('node_modules/')}.` |
| 58 | + ), |
| 59 | + request |
| 60 | + ); |
| 61 | + } else { |
| 62 | + callback(); |
| 63 | + } |
| 64 | + }); |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +module.exports = ModuleScopePlugin; |
0 commit comments