[英]I wanted to dynamically import images but I run the project I do not see the images
我正在創建 react 項目並決定轉義 create-react-app 並創建自己的自定義模板。 所以,然后我想通過這樣的導入動態添加圖像
import picture1 from "../../assets/picture1.jpg";
import picture3 from "../../assets/picture3.jpg";
import picture5 from "../../assets/picture5.jpg";
因此,為了實現這一點,我安裝了 file-loader 和 url-loader 並像這樣設置 webpack 配置:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
// webpack will take the files from ./src/index
entry: "./src/index",
// and output it into /dist as bundle.js
output: {
path: path.join(__dirname, "/build"),
filename: "bundle.js",
},
// adding .ts and .tsx to resolve.extensions will help babel look for .ts and .tsx files to transpile
resolve: {
extensions: [".ts", ".tsx", ".js"],
},
module: {
rules: [
{
test: /\.(ts|tsx)$/,
enforce: "pre",
use: [
{
options: {
eslintPath: require.resolve("eslint"),
},
loader: require.resolve("eslint-loader"),
},
],
exclude: /node_modules/,
},
// we use babel-loader to load our jsx and tsx files
{
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
},
{
test: /\.(png|jpg|gif)$/i,
use: [
{
loader: "url-loader",
options: {
limit: 8192,
},
},
],
},
{
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: "file-loader",
},
],
},
// css-loader to bundle all the css files into one file and style-loader to add all the styles inside the style tag of the document
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html",
}),
],
};
所以,請讓我知道我是否做對了一切? 為什么我在運行項目時看不到圖像?
您應該刪除文件加載器並改用 url-loader。 包括限制選項將導致所有超過 8192 字節的文件使用文件加載器。 所以包含文件加載器規則是多余的。 此外,8192 以下的任何內容都將轉換為數據 url 並包含在 bundle.js 中。
我會做這樣的事情:
module.exports = {
...
rules: {
{
test: /\.jpe?g$|\.gif$|\.png$/,
use: [
{
loader: 'url-loader',
options: {
mimetype: 'image/png',
limit: 8192
}
}
]
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.