웹 팩 파일 로더를 사용하여 이미지 파일을 로드하는 방법
웹 팩을 사용하여 reactjs 프로젝트를 관리하고 있습니다.웹팩으로 javascript로 이미지를 로드하고 싶다.file-loader
다음은 webpack.config.js 입니다.
const webpack = require('webpack');
const path = require('path');
const NpmInstallPlugin = require('npm-install-webpack-plugin');
const PATHS = {
react: path.join(__dirname, 'node_modules/react/dist/react.min.js'),
app: path.join(__dirname, 'src'),
build: path.join(__dirname, './dist')
};
module.exports = {
entry: {
jsx: './app/index.jsx',
},
output: {
path: PATHS.build,
filename: 'app.bundle.js',
},
watch: true,
devtool: 'eval-source-map',
relativeUrls: true,
resolve: {
extensions: ['', '.js', '.jsx', '.css', '.less'],
modulesDirectories: ['node_modules'],
alias: {
normalize_css: __dirname + '/node_modules/normalize.css/normalize.css',
}
},
module: {
preLoaders: [
{
test: /\.js$/,
loader: "source-map-loader"
},
],
loaders: [
{
test: /\.html$/,
loader: 'file?name=[name].[ext]',
},
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader?presets=es2015',
},
{test: /\.css$/, loader: 'style-loader!css-loader'},
{test: /\.(jpe?g|png|gif|svg)$/i, loader: "file-loader?name=/public/icons/[name].[ext]"},
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['babel-loader?presets=es2015']
}
]
},
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
},
output: {
comments: false,
},
}),
new NpmInstallPlugin({
save: true // --save
}),
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production")
}
}),
],
devServer: {
colors: true,
contentBase: __dirname,
historyApiFallback: true,
hot: true,
inline: true,
port: 9091,
progress: true,
stats: {
cached: false
}
}
}
이 행을 사용하여 이미지 파일을 로드하여 dist/public/icons 디렉토리에 복사하고 동일한 파일 이름을 유지했습니다.
{test: /\.(jpe?g|png|gif|svg)$/i, loader: "file-loader?name=/public/icons/[name].[ext]"}
하지만 나는 그것을 사용할 때 두 가지 문제가 있다.내가 달릴 때webpack
이미지 파일이 예상대로 dist/public/icons/디렉토리에 복사되었습니다.그러나 df55075baa16f3827a57549950901e90.png라는 이름의 dist 디렉토리에도 복사되었습니다.
프로젝트 구조는 다음과 같습니다.
또 다른 문제는 이 이미지 파일을 Import할 때 아래 코드를 사용했는데 브라우저에 표시되지 않는다는 것입니다.img 태그에 url 'public/icons/imageview_item_normal.png'을 사용하면 정상적으로 동작합니다.이미지 파일에서 가져온 개체를 사용하는 방법
import React, {Component} from 'react';
import {render} from 'react-dom';
import img from 'file!../../public/icons/imageview_item_normal.png'
export default class MainComponent extends Component {
render() {
return (
<div style={styles.container}>
download
<img src={img}/>
</div>
)
}
}
const styles = {
container: {
width: '100%',
height: '100%',
}
}
문제 #1에 대해서
webpack.config에서 file-loader를 설정하면 Import/require를 사용할 때마다 모든 로더에 대한 경로가 테스트되고 일치하는 경우 해당 로더를 통해 내용이 전달됩니다.당신의 경우, 그것은 일치했다.
{
test: /\.(jpe?g|png|gif|svg)$/i,
loader: "file-loader?name=/public/icons/[name].[ext]"
}
// For newer versions of Webpack it should be
{
test: /\.(jpe?g|png|gif|svg)$/i,
loader: 'file-loader',
options: {
name: '/public/icons/[name].[ext]'
}
}
그 때문에, 송신된 이미지를 볼 수 있습니다.
dist/public/icons/imageview_item_normal.png
수배된 행동이죠
해시 파일명도 취득할 수 있는 것은 인라인 파일로더를 추가하고 있기 때문입니다.다음과 같이 이미지를 Import합니다.
'file!../../public/icons/imageview_item_normal.png'.
프리픽스file!
는 파일을 다시 파일 저장소로 전달하며, 이번에는 이름 설정이 없습니다.
따라서 Import 대상은 다음과 같습니다.
import img from '../../public/icons/imageview_item_normal.png'
갱신하다
@cgatian에서 설명한 바와 같이 실제로 인라인파일 로더를 사용하는 경우 Webpack 글로벌Configuration을 무시하고 Import 앞에 느낌표 2개(!)를 붙일 수 있습니다.
import '!!file!../../public/icons/imageview_item_normal.png'.
문제 #2에 대해서
png Import 후img
variable은 파일 저장 경로만 보유합니다.즉, 다음과 같습니다.public/icons/[name].[ext]
(일명"file-loader? name=/public/icons/[name].[ext]"
) 출력 dir "dist"를 알 수 없습니다.이 문제는 다음 두 가지 방법으로 해결할 수 있습니다.
- "dist" 폴더에서 모든 코드를 실행합니다.
- 더하다
publicPath
출력 디렉토리(이 경우 ./dist)를 가리키는 출력 Configuration 속성.
예:
output: {
path: PATHS.build,
filename: 'app.bundle.js',
publicPath: PATHS.build
},
React JS 프로젝트에 이미지를 업로드하는 데 문제가 있었습니다.파일 로더를 사용하여 이미지를 로드하려고 했습니다.리액션에서도 Babel 로더를 사용하고 있었습니다.
웹 팩에서 다음 설정을 사용했습니다.
{test: /\.(jpe?g|png|gif|svg)$/i, loader: "file-loader?name=app/images/[name].[ext]"},
이렇게 하면 이미지를 로드하는 데 도움이 되지만 로드된 이미지가 약간 손상되었습니다.그 후, 조사 결과, 파일 로더가 바벨 로더를 장착했을 때 이미지가 파손되는 버그가 있는 것을 알게 되었습니다.
그래서 이 문제를 해결하기 위해 저는 URL 로더를 사용하려고 했습니다.
내 웹 팩을 다음 설정으로 업데이트했습니다.
{test: /\.(jpe?g|png|gif|svg)$/i, loader: "url-loader?name=app/images/[name].[ext]"},
그리고 다음 명령을 사용하여 이미지를 Import했습니다.
import img from 'app/images/GM_logo_2.jpg'
<div className="large-8 columns">
<img style={{ width: 300, height: 150 }} src={img} />
</div>
먼저 파일 로더를 설치합니다.
$ npm install file-loader --save-dev
이 규칙을 webpack.config.js에 추가합니다.
{
test: /\.(png|jpg|gif)$/,
use: [{
loader: 'file-loader',
options: {}
}]
}
또는 다음과 같이 쓸 수도 있습니다.
{
test: /\.(svg|png|jpg|jpeg|gif)$/,
include: 'path of input image directory',
use: {
loader: 'file-loader',
options: {
name: '[path][name].[ext]',
outputPath: 'path of output image directory'
}
}
}
그런 다음 단순 Import를 사용합니다.
import varName from 'relative path';
에는 jsx로 하다처럼 .<img src={varName} ..../>
....
입니다.
webpack5에서는 파일 로더 대신 자산 모듈을 사용할 수 있습니다.
Asset Modules is a type of module that allows one to use asset files (fonts, icons, etc) without configuring additional loaders.Asset Modules type replaces by adding asset/resource emits a separate file and exports the URL. Previously achievable by using file-loader.
module: {
rules: [
{
test: /\.png/,
type: 'asset/resource'
}
]
},
상세한 것에 대하여는, 메뉴얼을 참조해 주세요.
webpack.config.syslog
{
test: /\.(png|jpe?g|gif)$/i,
loader: 'file-loader',
options: {
name: '[name].[ext]',
},
}
anyfile.displaces 를 지정합니다.
<img src={image_name.jpg} />
이것은 심플한 Vue 컴포넌트의 작업 예입니다.
<template functional>
<div v-html="require('!!html-loader!./../svg/logo.svg')"></div>
</template>
언급URL : https://stackoverflow.com/questions/37671342/how-to-load-image-files-with-webpack-file-loader
'it-source' 카테고리의 다른 글
'useState' 후크를 사용할 때 React DevTools를 사용하여 React 다중 상태의 '필드' 이름을 볼 수 있는 방법이 있습니까? (0) | 2023.03.17 |
---|---|
각도 JS 사용자 지정 구분 기호 (0) | 2023.03.17 |
값을 기준으로 JSON 정렬 (0) | 2023.03.17 |
화면으로 돌아가면 React Native에서 useEffect가 호출되지 않음 (0) | 2023.03.17 |
Spring Boot : 데이터베이스에서 @Scheduled cron 값을 가져옵니다. (0) | 2023.03.17 |