【发布时间】:2018-01-17 18:10:06
【问题描述】:
您好,我使用 Webpack、TypeScript 和文件加载器建立了一个项目。
我的webpack.config.js:
const path = require('path');
module.exports = {
entry: './src/index.ts',
devtool: 'source-map',
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx']
},
module: {
rules: [
{
test: /\.ts$/,
enforce: 'pre',
loader: 'tslint-loader',
options: { /* Loader options go here */ }
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
},
{
test: /\.tsx?$/,
loader: 'awesome-typescript-loader'
}
]
},
devtool: 'inline-source-map',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
我的tsconfig.json:
{
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"moduleResolution": "node",
"compilerOptions": {
"noImplicitAny": true,
"removeComments": true
},
"sourceMap": true,
"outDir": "dist",
"baseUrl": ".",
"paths": {
"*": [
"node_modules/*",
"src/types/*"
]
},
"exclude": [
"node_modules"
]
}
还有我的index.ts:
import * as _ from 'lodash';
import * as PIXI from 'pixi.js';
const renderer = PIXI.autoDetectRenderer(256, 256,
{ antialias: false, transparent: false, resolution: 1 });
document.body.appendChild(renderer.view);
const stage = new PIXI.Container();
renderer.render(stage);
上述星座按预期将舞台渲染到index.html。
现在我在src/images/ 文件夹中添加了一个bs.png 文件,现在我的项目结构如下所示:
据我了解,这个bs.png 被加载为文件/dist/14145c56ece7799954586ba6f8464dbb.png。我的麻烦就从这里开始。我尝试按如下方式加载图像。首先,我创建了一个custom.d.ts,其中包含一个用于加载.png 文件的模块声明:
declare module "*.png" {
const content: any;
export default content;
}
现在在index.ts 我通过import * as Image from './images/bs.png'; 加载它。生成的Image 是函数类型,console.log(Image) 的输出是14145c56ece7799954586ba6f8464dbb.png。不幸的是,我无法像这样加载 Pixi 纹理:
const text = new PIXI.Texture(Image);
通过这条线我得到:
src/index.ts(12,31): error TS2345: Argument of type 'typeof "*.png"' is not assignable to parameter of type 'BaseTexture'.
Property 'touched' is missing in type 'typeof "*.png"'.
我明白了。我也不能用:
const texture = PIXI.utils.TextureCache[Image];
虽然 Image 似乎确实返回了文件路径。我尝试使用 webpack 创建的 png 的文件路径加载图像,但纹理仍然是 undefined。
我真的不确定这里的真正问题是什么。我需要运行服务器(例如快递)还是我只是错过了一些东西?顺便说一句,这是使用awesome-typescript-loader 的npm run build 命令的输出:
> webpack
Hash: 45f5667bd75205a328bf
Version: webpack 3.4.1
Time: 3297ms
Asset Size Chunks Chunk Names
14145c56ece7799954586ba6f8464dbb.png 4.07 kB [emitted]
bundle.js 4.83 MB 0 [emitted] [big] main
[16] (webpack)/buildin/global.js 509 bytes {0} [built]
[37] (webpack)/buildin/module.js 517 bytes {0} [built]
[88] ./src/index.ts 851 bytes {0} [built]
[192] ./src/images/bs.png 82 bytes {0} [built]
+ 189 hidden modules
【问题讨论】:
-
好吧,至少我建议在使用之前确保已加载图像。由于在示例中您尝试从 TextureCache 检索图像,但我看不到您实际将其添加到缓存的位置。所以你至少可以使用加载器:pixijs.download/dev/docs/PIXI.loaders.Loader.html。所以像:loader.add('bunny', 'data/bunny.png'); loader.load((loader, resources) => { Create the sprite from the image in cache }) ... 同样在创建纹理时,您可能应该使用:let texture = PIXI.Texture.fromImage,而不是构造函数
标签: typescript webpack pixi.js webpack-file-loader