在Vue应用中工作我正在尝试从node_modules中的一对依赖项动态导入css文件。
使用require('path')
与静态字符串工作良好,并加载我的css文件。当我试图将函数参数传递给require()函数时,它就不起作用了。
const getFontDeclaration = (path) => {
{
return new Promise((resolve) => {
// a static string works fine
require('@foo/own-package-name/dist/assets/css/font-face.css');
// using an argument does not work
require(path);
// import(path)
// does not work either
// while this work fine too
import('@foo/own-package-name/dist/assets/css/font-face.css')
.then(() => {
resolve();
})
});
}
};
有线索或方向吗?import()和require()
的使用有点混淆require
不能动态地完美工作,因为webpack不知道你的path
参数的路径。然而,如果你在require
中添加某种模板文字,它将工作(例如my-fonts/${path}
)。
import
动态地导入一些东西。
您可以在这里找到Webpackimport
功能的更多详细信息。
为清楚起见
const getFontDeclaration = (path) => {
// using a variable directly will not work
require(path);
// removing a part of the path and prepending it with a static string will work
const reqPath = url.replace('@foo/', '');
require(`@foo/${reqPath}`);
}