圖片的引用:
<img src="../assets/image/setting.png"/>
目錄結構:
#寫的相對路勁,為什麼圖片沒有顯示出來?
console提示:
#webpack:
var path = require("path");
var webpack = require("webpack");
var HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: [
"react-hot-loader/patch",
"webpack-dev-server/client?http://0.0.0.0:3000",
"webpack/hot/only-dev-server",
"babel-polyfill",
"whatwg-fetch",
"./src/index"
],
devServer: {
hot: true,
contentBase: path.resolve(__dirname, "dist"),
port: 3000,
host: "0.0.0.0",
publicPath: "/",
historyApiFallback: true,
disableHostCheck: true,
proxy: {
"/agent": {
target: "http://dn4:19000",
changeOrigin: true,
},
"/api": {
target: "http://dn4:19989",
changeOrigin: true,
},
"/sign": {
target: "http://dn4:19000",
changeOrigin: true,
},
"/file": {
target: "http://dn4:19000",
changeOrigin: true,
},
}
},
output: {
path: path.join(__dirname, "dist"),
publicPath: "/",
filename: "app.[hash].js"
},
devtool: "eval",
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
options: {
presets: [
["es2015", {"modules": false}],
"stage-0",
"react"
],
plugins: [
"transform-async-to-generator",
"transform-decorators-legacy",
["import", {"libraryName": "antd", "style": true}]
]
}
},
{
test: /\.scss|css$/,
use: [
"style-loader",
"css-loader",
"postcss-loader",
"resolve-url-loader",
"sass-loader?sourceMap"
]
},
{
test: /\.less$/,
use: [{
loader: "style-loader" // creates style nodes from JS strings
}, {
loader: "css-loader" // translates CSS into CommonJS
}, {
loader: "less-loader", options: {
modifyVars: {
"primary-color": "#0183ff",
"font-size-base": "16px",
}
} // compiles Less to CSS
}]
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
use: [
"file-loader?hash=sha512&digest=hex&name=[hash].[ext]",
{
loader: "image-webpack-loader",
options: {
progressive: true,
optimizationLevel: 7,
interlaced: false,
pngquant: {
quality: "65-90",
speed: 4
}
}
}
]
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: "url-loader?limit=10000&mimetype=application/font-woff"
},
{
test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: "file-loader"
}
]
},
plugins: [
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({hash: false, template: "./index.hbs"}),
new webpack.ContextReplacementPlugin(/moment[\/\]locale$/, /nb/)
]
};
原因找到了:
contentBase: path.resolve(__dirname, "dist"),
路勁應該寫相對於dist的路徑
但是現在又有一個問題!這樣寫在生產環境肯定是顯示不了圖片的!
我不打算將靜態資源放在/dist下,樓下說了static檔案的方法,這個應該要設定webpack,有沒有朋友分享一下
靜態資源的問題已解決,解決方案:
使用webpack的一個插件,生產環境編譯時可以將/static目錄的文件拷貝到/dist目錄下
開發的時候的時候webpack-devserver設定:
這樣在程式碼裡面只要寫絕對路徑/static/..就行了
你寫img的檔案在哪裡啊? "../assets/image/setting.png"這個只有你寫img的檔案在components目錄下才有效.
如果是使用vue-cli的webpack模板,會被轉成絕對路徑,如:
/images/setting.png
,建議將圖片放在static資料夾下。固定路徑都放在/static下面把,唯一打包前打包後位置不變的地方