我迁移了一个我一直致力于Webpack 2的项目,这让我很头疼。但我已经让我的项目使用Webpack dev服务器进行预览,除了它不会显示我的图像。我得到的只是浏览器控制台GET http://localhost:8080/logo.jpg 404 (Not Found)
并在MacOS控制台中:
ERROR in ./js/components/Global/Menu.jsx Module not found: Error: Can't resolve 'logo.jpg' in '/Users/user1/Documents/AAA/app/js/components/Global'
这是我的Webpack配置:
const path = require('path');
module.exports = {
context: __dirname + "/app",
entry: {
app: "./js/app.js",
javascript: "./js/app.js",
html: "./index.html",
},
output: {
//output.path: "[name].js",
path: __dirname + "/dist",
filename: "[name].js"
},
resolve: {
alias: { 'react/lib/ReactMount': 'react-dom/lib/ReactMount' },
extensions: [ '*', '.js', '.jsx', '.json'],
modules:[__dirname, './app/js', 'node_modules'],
},
module: {
rules: [
{
test: /\.jsx?$/,
include: [
path.resolve(__dirname, "app")
],
loaders: ["babel-loader"],
},
{
test: /\.html$/,
loader: ["file-loader?name=[name].[ext]"],
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
include : path.join(__dirname, 'app'),
loader : 'url-loader?limit=30000&name=images/[name].[ext]'
}
],
},
}
迁移打破了多个图像但是我只能使用它作为修复其他图像的基础:
import React, { Component } from 'react';
import { Link } from 'react-router';
import Logo from "logo.jpg";
export default class Menu extends Component {
render() {
return (
<div className='Menu' id='Menu'>
<img src={Logo}></img>
<Link to='/'>Home</Link> <Link to='/about'>Clothing</Link> <Link to='/Cart'>Cart</Link>
<hr />
</div>
);
}
}
我应该使用url('logo.jpg')
吗?为什么开发服务器没有找到图像并显示它们?
修改
试过:
let img = new Image();
img.src = require('logo.jpg');
和<img src={img.src}>
,但它给了我同样的错误。
答案 0 :(得分:0)
您应该查看本指南: https://webpack.js.org/guides/migrating/
您使用旧格式配置为webpack1,配置为webpack2如下;
module: {
rules: [
{
test: /\.jsx?$/,
include: [
path.resolve(__dirname, "app")
],
use: ["babel-loader"],
},
{
test: /\.html$/,
use: [{
loader: 'file-loader',
options: {
name: '[name].[ext]'
}
}],
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
include : path.join(__dirname, 'app'),
use: [{
loader: 'url-loader',
options: {
limit: 30000,
name: '[name].[ext]'
}
}]
}
],
},
答案 1 :(得分:0)
我想我知道这个问题。导入时,您没有为图像指定正确的路径。尝试为图像文件夹添加别名
resolve: {
alias: {
'react/lib/ReactMount': 'react-dom/lib/ReactMount',
images: '/Users/user1/Documents/AAA/app/js/components/Global', // absolute path to images folder
},
extensions: [ '*', '.js', '.jsx', '.json'],
modules:[__dirname, './app/js', 'node_modules'],
},
然后导入你的图像:
import Logo from 'images/logo.jpg';
答案 2 :(得分:0)
指定绝对的publicPath为我工作。 Reference
{
test: /\.(png|jpg)$/,
include: path.join(__dirname, '/app'),
loader: 'url-loader',
query: {
outputPath: path.join(__dirname, '/app/dist'),,
publicPath: 'http://localhost:8080/',
emitFile: true,
},
},
答案 3 :(得分:0)
您的webpack配置未明确声明output.publicPath
设置。基本配置可能如下:
output: {
publicPath: '/',
path: __dirname + "/dist",
filename: "[name].js"
},
进一步考虑: ,因为您的logo.jpg
位于组件的同一目录中,为什么不使用./
相对路径导入它?
import Logo from "./logo.jpg";