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个)目录,而不是一个。
您可以创建加载程序以将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;
有关更多信息,请参见编写webpack加载器。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句