【发布时间】:2018-02-01 13:04:30
【问题描述】:
我有一个 react 项目,我在其中使用 webpack 3.10.0 和文件加载器 1.1.6 将一些图像和 json 文件移动到我的分发文件夹中。
Webpack 按预期发出文件,但 react 接收到我的 json 和图像资产的错误 url
我的标记看起来像:
<img src="../images/helloworld_a49183cf48e4a0f12aa2124fe2ed9d3a.png"
alt="Hello World!!">
但应该是:
<img src="/assets/images/helloworld_a49183cf48e4a0f12aa2124fe2ed9d3a.png"
alt="Hello World!!">
我的文件夹结构如下所示:
C:.
├───dist
│ └───assets
│ ├───css
│ ├───data
│ ├───images
│ └───js
├───src
│ ├───css
│ ├───data
│ ├───images
│ └───js
│ ├───actions
│ ├───components
│ ├───containers
│ └───reducers
└───tests
我认为文件加载器 publicPath 应该解决这个问题,但似乎我误解或我的配置有问题。 有人能帮帮我吗?
webpack.config.js
var path = require('path');
const ExtractCSS = require("extract-text-webpack-plugin");
module.exports = {
entry: [
'./src/js/index.js'
],
output: {
path: path.resolve(__dirname, 'dist/assets/js'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env','react']
}
}
},
{
test: /\.scss$/,
loader: ExtractCSS.extract('css-loader!sass-loader')
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
name (file) {
/*if (env === 'development') {
return '[path][name].[ext]'
}*/
return '[name]_[hash].[ext]'
},
publicPath: '/assets/images/',
outputPath: '../images/'
}
}
]
},
{
test: /\.json$/,
use: [
{
loader: 'file-loader',
options: {
name (file) {
/*if (env === 'development') {
return '[path][name].[ext]'
}*/
return '[name].[ext]'
},
publicPath: '/assets/data/',
outputPath: '../data/'
}
}
]
}
]
},
plugins: [
new ExtractCSS('../css/app.css', {
allChunks: true
})
],
resolve: {
extensions: ['.js', '.jsx']
},
//devtool: 'eval-source-map',
devServer: {
historyApiFallback: true,
contentBase: './dist/'
}
};
【问题讨论】:
标签: reactjs webpack webpack-file-loader