webpack中是否有一种方法可以限制可以导入哪些文件?
说我想能够导入同一目录以及父目录中的文件,但是该父目录之上没有任何内容吗?例如:
这些作品
import { blah } from "./script.js";
import { blah2 } from "./../gui/textbox.js";
import { blah3 } from "./../I/can/go/as/deep/down/as/I/want/here.js";
但这是行不通的
import { passwords } from "./../../passwords.txt";
因为该目录将上升到两个(或x个)目录,而不仅仅是一个。
答案 0 :(得分:2)
您可以创建加载程序,以将webpack导入限制为特定文件。
// file: webpack.config.js
const path = require('path');
module.exports = {
...
module: {
rules: [
{
test: /\.js$/,
use: [
{
loader: path.resolve('my-webpack-loader.js'),
options: {/* ... */}
}
]
}
]
}
};
如果资源文件位于./src
和./node_modules
目录或您选择的任何目录之外,则抛出该异常。
// file: my-webpack-loader.js
const { getOptions } = require('loader-utils');
const validateOptions = require('schema-utils');
const path = require('path');
const schema = {
type: 'object',
properties: {
test: {
type: 'string'
}
}
};
function handler(source) {
const options = getOptions(this);
if(this.resourcePath.indexOf(path.resolve('./node_modules')) !== 0) {
if(this.resourcePath.indexOf(path.resolve('./src')) !== 0) {
throw `Reseource loading restricted for ${this.resourcePath}`;
}
}
validateOptions(schema, options, 'My Webpack Loader');
return source;
}
module.exports = handler;
有关更多信息,请参见writing a webpack loader。
答案 1 :(得分:0)
react-dev-utils
为此有一个plugin。
此Webpack插件可确保从应用程序源进行相对导入 目录不会到达它的外部。
var path = require('path');
var ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
module.exports = {
// ...
resolve: {
// ...
plugins: [
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
// ...
],
// ...
},
// ...
};