reactjs - 在 ReactJs 应用程序中使用 webpack 处理资产
问题描述
我需要在我的 React 组件中加载图像:
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const bundleOutputDir = './wwwroot/dist';
module.exports = (env) => {
const isDevBuild = !(env && env.prod);
return [{
stats: { modules: false },
entry: { 'main': './ClientApp/boot.tsx' },
resolve: { extensions: ['.js', '.jsx', '.ts', '.tsx'] },
output: {
path: path.join(__dirname, bundleOutputDir),
filename: '[name].js',
publicPath: 'dist/'
},
module: {
rules: [
{ test: /\.tsx?$/, include: /ClientApp/, use: 'awesome-typescript-loader?silent=true' },
{ test: /\.css$/, use: isDevBuild ? ['style-loader', 'css-loader'] : ExtractTextPlugin.extract({ use: 'css-loader?minimize' }) },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, loader: 'file-loader' },
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000&mimetype=application/font-woff" },
{ test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader" }
]
},
plugins: [
new CheckerPlugin(),
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
})
].concat(isDevBuild ? [
// Plugins that apply in development builds only
new webpack.SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(bundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
// Plugins that apply in production builds only
new webpack.optimize.UglifyJsPlugin(),
new ExtractTextPlugin('site.css')
])
}];
};
在组件中,我尝试像这样加载图像:
import Logo from '../css/images/logo.png';
但它没有用!
如何编辑配置 webpack 以处理资产,尤其是图像?
谢谢,
解决方案
从您的示例中,我认为您的图像文件是本地存储的。created-react-app
您是否使用或应用程序创建了 reactjs 应用ejected
程序。
import Logo from '../css/images/logo.png'
并使用<img src={Logo} className="blue"/>
或者<img src={require('../css/images/logo.png')} className="blue"/>
推荐阅读
- sql - 在聚合函数中指定列值与使用 WHERE 子句
- php - Laravel Echo Server 给出错误未处理错误事件:错误:连接 ECONNREFUSED
- html - Swift:NSAttributeString 不正确的 HTML 结果
- javascript - 返回承诺的Javascript顺序函数
- php - 数据库已连接,但数据未存储在 xamp 服务器中
- android - 切换到多窗口模式时,我的 Android 应用程序崩溃
- ios - iOS当按下按钮“下一步”加载新行表单解析Swift
- python - Python中各种数据库的单一API
- java - 从 Fragment 中的 Adapter 获取 imageview
- git - git clone 或通过慢速网络拉取一个巨大的 repo 以致命的 EOF 结束