Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用webpack处理外部模块中的url(…)_Webpack - Fatal编程技术网

如何使用webpack处理外部模块中的url(…)

如何使用webpack处理外部模块中的url(…),webpack,Webpack,我有一个在外部模块X(node_模块中的另一个包)中定义的样式,如: src my-module.js 节点单元 x、 js 该模块包含以下内容: // FIXME: remove disable comment after https://github.com/palantir/tslint/issues/3987 is released // Fonts and other resources are relative to the module that imports t

我有一个在外部模块X(node_模块中的另一个包)中定义的样式,如:

  • src
    • my-module.js
  • 节点单元
    • x、 js
该模块包含以下内容:

// FIXME: remove disable comment after https://github.com/palantir/tslint/issues/3987 is released
// Fonts and other resources are relative to the module that imports this style module, so calculate the URL
let url = import.meta.url;
url = url.replace(url.split("/").pop(), "");
/* tslint:enable */
// See also issue #1433 about font loading
export let typo = `

@font-face {
    font-family: 'HelveticaNeueLTStd-Roman';
    src: url('${url}/../../../fonts/Helvetica_Neue/398D5F_0_0.woff2')  format('woff2');
};
如何让webpack处理
url()
内容,以便webpack替换url并将图像/字体等复制到输出目录?我知道加载的css中也有相同的逻辑,但在我的用例中,样式包含在JS模块中


谢谢。

您需要在您的网页配置中建立一个文件加载器()。文件加载器将文件解析为url,并将该文件发送到输出目录中

{
‘测试’:/\(woff(2)| ttf | eot)(\?v=\d+\.\d+\.\d+)?$/,
“排除”:/node_模块/,
“使用”:[
{
“加载程序”:“文件加载程序”,
“选项”:{
“名称”:“[name].[ext]”,
“outputPath”:“some/font/folder”/`
}
}
]
}
然后,您可以简单地
require()
该字体文件,并在
url()
中使用它:

const font=require('/actual/source/location/of/font/Helvetica_Neue/398D5F_0_0.woff2');
导出let输入错误=`
@字体{
字体系列:“Helveticaneultstd Roman”;
src:url('${font}')格式('woff2');
};
`;

不要这样做。试图使Webpack足够智能,以便在JS文件中找到以后可能用作内联样式的每个字符串是没有意义的

相反,您应该使用将依赖项的资产移动到预期的位置。例如,我使用了一个名为铯的包,在配置中

从“复制网页包插件”导入CopyPlugin;
导出常量铯源=解析(“./node_模块/铯/源”);
导出常量cesiumTarget=“CesiumStatic”;
module.exports={
// ...
插件:[
新CopyPlugin({
模式:[{
发件人:join(cesiumSource,“资产”),
致:cesiumTarget+“/Assets”,
}]
})
]
}
这会将整个资产树复制到
/dist/CesiumStatic/Assets
。这个包在运行时有一个机制告诉它资产应该在哪里,并使用我给它的路径为字体、JSON数据、图像等构建URL


您的依赖项看起来不太可配置,只希望它的内容是
/font/
。您需要设置一个CopyPlugin,从存储字体文件的任何位置(大概是,
/node\u modules/x/fonts/
?)获取字体文件,并将其放在构建目录中。

感谢您的回复。正如我提到的,代码在一个外部包中,我不能更改它的代码。有没有其他方法可以做到这一点?例如,
polymer网页包加载器
也可以完成这项工作,但仅适用于polymer元素。