I've got a project that uses Typescript 2.4.1, Webpack 2.6.1, and I'm having some issues getting relative paths to load my images correctly.
If I put an image in the same folder as my .ts
file that loads it, I can get it to work:
const background = require("./background.png");
console.log(background);
So this works:
src
Book.ts
background.png
But I can't figure out how to make file loader find the image with this structure:
src
Book.ts
assets
background.png
I tried setting the publicPath
in the file-loader options as described here but I couldn't get the file to load at all that way no matter what combinations of absolute and relative paths I tried.
Here's my webpack.config.js file. (I removed some parts because it is long.)
module.exports = {
entry: {
app: [
path.resolve(__dirname, './src/main.ts')
],
vendor: ['pixi', 'p2', 'phaser', 'webfontloader']
},
output: {
pathinfo: true,
path: path.resolve(__dirname, 'dist'),
publicPath: './dist/',
filename: 'bundle.js'
},
module: {
rules: [
{test: /\.ts$/, enforce: 'pre', loader: 'tslint-loader', options: {emitErrors: true, failOnHint: true}},
{test: /\.ts$/, loader: 'ts-loader'},
{test: /pixi\.js/, use: ['expose-loader?PIXI']},
{test: /phaser-split\.js$/, use: ['expose-loader?Phaser']},
{test: /p2\.js/, use: ['expose-loader?p2']},
{test: /\.(png|svg|jpg|gif|mp3|wav|mp4)$/, use: [{
loader: 'file-loader',
options: {
outputPath: 'assets/'
}
}]},
{enforce: "pre", test: /\.js$/, loader: "source-map-loader"}
]
},
node: {
fs: 'empty',
net: 'empty',
tls: 'empty'
}
}
And here's my typescript require declaration:
declare let require: {
<T>(path: string): T;
(paths: string[], callback: (...modules: any[]) => void): void;
ensure: (paths: string[], callback: (require: <T>(path: string) => T) => void) => void;
};
(I tried getting nice ES6 imports working, but that didn't go well.)
I tried it with file-loader and it didnt really work...
try using "url-loader" like this in webpack.config:
// "url" loader works like "file" loader except that it embeds assets
// smaller than specified limit in bytes as data URLs to avoid requests.
// A missing `test` is equivalent to a match.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]',
},
},
Then you can "just" use this to get the path which you can then use:
const imageSrc = import('./relativePathToImgFile');
Edit: And dont forget to add url-loader to package.json :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.