Angular2 + Webpack不显示图像 [英] Angular2 + webpack not displaying images
问题描述
我遵循了 Angular2 Webpack教程,但看起来该应用程序无法加载任何图像.这是我的应用程序的目录结构:
I have followed the Angular2 webpack tutorial, but seems like the app cannot load any image. This is the directory structure of my app:
...
/dist/
/src/assets/images/
/src/assets/css/
...
这是文件 config/webpack.common.js 中的Webpack配置:
And this is the webpack configuration on file config/webpack.common.js:
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var helpers = require('./helpers');
module.exports = {
entry: {
'polyfills': './src/polyfills.ts',
'vendor': './src/vendor.ts',
'app': './src/main.ts'
},
resolve: {
extensions: ['.ts', '.js']
},
module: {
rules: [
{
test: /\.ts$/,
loaders: [{
loader: 'awesome-typescript-loader',
options: { configFileName: helpers.root('src', 'tsconfig.json') }
} , 'angular2-template-loader']
},
{
test: /\.html$/,
loader: 'html-loader'
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: 'file-loader?name=assets/[name].[hash].[ext]'
},
{
test: /\.css$/,
exclude: helpers.root('src', 'app'),
loader: ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: 'css-loader?sourceMap' })
},
{
test: /\.css$/,
include: helpers.root('src', 'app'),
loader: 'raw-loader'
}
]
},
plugins: [
// Workaround for angular/angular#11580
new webpack.ContextReplacementPlugin(
// The (\\|\/) piece accounts for path separators in *nix and Windows
/angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
helpers.root('./src'), // location of your src
{} // a map of your routes
),
new webpack.optimize.CommonsChunkPlugin({
name: ['app', 'vendor', 'polyfills']
}),
new HtmlWebpackPlugin({
template: 'src/index.html'
})
]
};
现在,如果我尝试向模板中添加一些图像:
Now if I try to add some image to the templates:
<img src="/assets/images/hp-logo.png">
在编译过程中(运行 npm start
时),我总是遇到以下错误:
I am always getting the following error during compilation (when running npm start
):
ERROR in ./src/app/templates/dashboard.component.html
Module not found: Error: Can't resolve './assets/images/hp-logo.png' in '/frontend/src/app/templates'
@ ./src/app/templates/dashboard.component.html 1:582-620
@ ./src/app/components/dashboard.component.ts
@ ./src/app/modules/app.module.ts
@ ./src/main.ts
@ multi (webpack)-dev-server/client?http://localhost:3000 ./src/main.ts
我想这与文件加载器有关,但是尝试了不同的配置后,我无法使其正常工作.
I guess it has something to do with the file-loader but after trying different configuration I couldn't get it to work.
有人可以帮我这个忙吗?
Somebody can help me out on this one?
推荐答案
您应该编写相对于模板位置的图像路径.如果您的模板是/src/module1/template.html,则您的图片位置应为
You should write the image path relative to the template location. If your template is e.g. at /src/module1/template.html then your image location should be
<img src="../assets/images/hp-logo.png">
这篇关于Angular2 + Webpack不显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!