是否可以在node.js环境下动态更改webpack中的镜像资源路径



我的React应用程序使用的是4.35.3版本的Webpack。

我有一个反应组件,我用来导入我的应用程序徽标:

import logo from 'images/logo.png';

const AppLogo = () => (
<image src={logo} alt="myAppLogo" />
);

我希望根据构建应用程序的服务器的env为应用程序加载不同的徽标。

例如,如果我在本地提供应用程序,我会得到一个与生产中不同的徽标。

我希望将图像导入到webpack中,而不是通过服务器上的公共访问路径导入,这样在应用程序环境中就不会有任何不相关的图像。

所以我试图通过webpack构建来解决这个问题。

如何根据process.env.MY_ENV_VAR动态指定图像路径?这样我就可以导入

- production
- images
- appLogo.png
- development
- images
- appLogo.png

我的webpack图片加载看起来是这样的:

module: {
rules: [{
test: /.(jpg|png|gif)$/,
use: [
{
loader: 'file-loader',
options: {
query: {
name: '[name].[ext]',
},
},
},
{
loader: 'image-webpack-loader',
options: {
query: {
progressive: true,
optimizationLevel: 7,
interlaced: false,
pngquant: {
quality: '65-90',
speed: 4,
},
},
},
},
],
}]

我们在angular应用程序中也有类似的要求。有点晚了,但由于我只花了3天时间讨论这个问题,这可能对其他人有用。关键在于:https://www.npmjs.com/package/file-replace-loader

File structrure:
-webapp
- images
-webapp
- profile
- profileA 
- images
-profileB
- images  


{
test: /.(jpe?g|png|gif|svg|woff2?|ttf|eot|mp3|pdf)$/i,
use: [{
loader: 'file-loader', options: {
digest: 'hex',
hash: 'sha512',
name: 'content/[hash].[ext]'
}
}, {
loader: 'file-replace-loader', options: {
condition: 'if-replacement-exists',
replacement(resourcePath) {
let path = resolve(resourcePath);
if (path.indexOf(`webapp${sep}images${sep}`) !== -1) {
path = resourcePath.replace(`webapp${sep}images${sep}`, `webapp${sep}profile${sep}${process.env.PROFILE}${sep}images${sep}`);
}
return path
}
}
}],
},

通过这种方式更改文件加载器,我们实现了用webapp/profile/[profileNameFromEnv]/images中的文件替换webapp/images中的所有文件(如果存在的话(。

重要的是使用基于操作系统的文件分隔符进行检查您可以从路径const { sep } = require('path');获得什么

最新更新