简体   繁体   English

Webpack是否需要动态文件路径?

[英]Dynamic file path in require with webpack?

This works fine when i manually request the file using require , however the moment i use the exact same request, but change the string so that it's split up with variables it fails. 当我使用require手动请求文件时,此方法工作正常,但是当我使用完全相同的请求,但更改字符串以使其与变量分开时会失败。

This works great: 这很好用:

module.exports = (function() {
    var $svg = require('svg-inline!../../assets/svgs/global/connected.svg');
    console.log($svg);
}());

However if I was to do this: 但是,如果我要这样做:

module.exports = (function() {
    var $path = '../../assets/svgs/global/';
    var $svg = require('svg-inline!'+$path+'connected.svg');
    console.log($svg);
}());

It fails and says inside the console: 它失败并在控制台内说:

Uncaught Error: Cannot find module "."

I guess my question is why can't you concatenate strings like i have here? 我想我的问题是,为什么不能像我在这里那样连接字符串?

I think you have to look into webpack context . 我认为您必须研究webpack 上下文 Basically when you try to require something that contains an expression, webpack will create a context. 基本上,当您尝试要求包含表达式的内容时,webpack会创建一个上下文。 That expression will be treated as a regular expression and it doesn't work as you may expect. 该表达式将被视为正则表达式,并且无法正常运行。

Try: 尝试:

require(`svg-inline!${$path}connected.svg`)

and if you need more variable in your dynamic path try split require: 如果您需要在动态路径中添加更多变量,请尝试分割要求:

 function getIcon(name) { const [category, filename] = name.split(":"); if (filename) { return require(`one_directory/icons/${category}/${filename}.svg`); } else { return require(`two_directory/icons/${name}.svg`); } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM