使用require()从node_modules中导入CSS文件



在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}`);
}

最新更新