css - Webpack React 构建后对图像的模糊引用
问题描述
我正在使用 webpack 构建我的应用程序,到目前为止它越来越好。我的模块似乎都没有损坏。旁白:我只是怀疑,因为我对这个东西如何将我的 150mb React 应用程序变成 2mbs 感到非常困惑,并且几乎不知道这东西是如何工作的。
我遇到的问题是我的图像或大部分 CSS 都没有正确加载。这是一个示例元素
<img class="searched-user-icon bump-icon" src="export default __webpack_public_path__ + &quot;src/static/pointingfinger.svg&quot;;" alt="pointingfinger">
这不会渲染图像。它给了我一个 404。现在,如果我在浏览器开发工具中将其更改为此:
<img class="searched-user-icon bump-icon" src="src/static/pointingfinger.svg" alt="pointingfinger">
它有效,这是有道理的。但当然我需要解决这个问题,以便图像在构建后正常显示。我在我的反应组件文件中导入我的图像:import pointingfinger from '../static/pointingfinger.svg';
我没有找到很多关于这种奇怪现象的文档。我想知道是否有人知道可以向我解释发生了什么,这将不胜感激。此外,我想简单地复制我的 css,基于在构建期间相对地找到 css 文件的位置,就像我对文件加载器所做的那样。我可以手动设置它以将它找到的所有 css 放入一个文件夹中,但这似乎不太“动态”。下面是我的 webpack 配置
module.exports = {
entry: "./src/index.js", // The entry point for the application
output: {
path: path.join(__dirname, '/dist'),
publicPath: '/',
filename: 'index_bundle.js' // This will be the created bundle file that webpack creates for react to use in production
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
},
{
test: /\.svg$/, use: 'svg-inline-loader'
},
{
test: /\.css$/i, use: [ 'style-loader', 'css-loader' ]
},
{
test: /\.(png|jpe?g|gif|svg)$/i, loader: 'file-loader', options: { name: '[path][name].[ext]' }
}
]
},
target: ['web', 'es5'],
plugins: [
new HtmlWebpackPlugin({ template: './public/index.html'}),
new webpack.ProvidePlugin({
process: 'process/browser'
})
],
mode: 'production' // Can be set to development or production. Webpack will minify code and strip warnings
}
编辑:看起来配置<img src={pointingfinger}></img>
在我的代码中引用这样的源时出现问题。我打赌一个简单的插件就足够了。当我发现一些东西时,我会更新。
edit2:使用插件“plugin-transform-react-jsx”似乎不能解决这个问题。
解决方案
我通过删除解决了这个问题
{
test: /\.svg$/, use: 'svg-inline-loader'
}
虽然许多其他教程都说要使用它,但我的 React 应用程序主要将它们用作 img 和 src 对它们的引用。它们大多是在组件的顶部导入import theimgvar from 'a/path/to/img.svg';
并像这样引用src={theimgvar}
所以只需要定义文件加载器来加载 svg 以及我已经在那里
{
test: /\.(png|jpe?g|gif|svg)$/i,
loader: 'file-loader',
options: { name: '[path][name].[ext]' }
}
推荐阅读
- java - 通过在方法中将对象作为参数传递来查找对象中的元素
- c# - Microsoft.Reporting.WebForms:Excel 导出数据行折叠,部分数据丢失
- php - Symfony 4 - 找不到在“App\Entity\User”上声明的实体监听器“App\Entity\UserListener”
- c - C输入getch(),当没有像Snake(游戏)那样按下时跳过
- node.js - 使用 Firebase Admin SDK (NodeJS) 将数据导入 Firestore 不适用于所有集合
- mongodb - 使用 $lookup 运算符连接条件
- windows-10 - 混合命令给出“打开 ETS 文件时出错”
- java - 如何修复 NullPointerException,jsoup 元素
- java - 将用户发送到 ChatActivity
- python - 为什么 dask 在 CUDA 函数上不返回任何内容?