webpack无法导入图像(在打字稿中使用express和angular2)

Sah*_*rma 20 urlloader express typescript webpack angular

我无法在headercomponent.ts中导入图像.我怀疑这是因为我在编译ts(使用webpack ts loader)时出错了,因为同样的事情与react(其中组件是用es6编写的)一起工作

错误位置是

//headercomponent.ts
import {Component, View} from "angular2/core";
import {ROUTER_DIRECTIVES, Router} from "angular2/router";
import {AuthService} from "../../services/auth/auth.service";
import logoSource from "../../images/logo.png"; //**THIS CAUSES ERROR**  Cannot find module '../../images/logo.png'

@Component({
    selector: 'my-header',
    //templateUrl:'components/header/header.tmpl.html' ,
    template: `<header class="main-header">
  <div class="top-bar">
    <div class="top-bar-title">
      <a href="/"><img src="{{logoSource}}"></a>
    </div>
Run Code Online (Sandbox Code Playgroud)

我的webpack配置是

// webpack.config.js
'use strict';

var path = require('path');
var autoprefixer = require('autoprefixer');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var basePath = path.join(__dirname,'public');
//const TARGET = process.env.npm_lifecycle_event;
console.log("bp " + basePath)
module.exports = {
  entry: path.join(basePath,'/components/boot/boot.ts'),
  output: {
    path: path.join(basePath,"..","/build"), // This is where images AND js will go
    publicPath: path.join(basePath,"..","/build/assets"),
   // publicPath: path.join(basePath ,'/images'), // This is used to generate URLs to e.g. images
    filename: 'bundle.js'
  },
  plugins: [
    new ExtractTextPlugin("bundle.css")
  ],
  module: {
    preLoaders: [ { test: /\.tsx$/, loader: "tslint" } ],
    //
    loaders: [
      { test: /\.(png!jpg)$/, loader: 'file-loader?name=/img/[name].[ext]'  }, // inline base64 for <=8k images, direct URLs for the rest
      {
        test: /\.json/,
        loader: 'json-loader',
      },
      {
        test: /\.ts$/,
        loader: 'ts-loader',
        exclude: [/node_modules/]
      },
      {
        test: /\.js$/,
        loader: 'babel-loader'
      },
      {
        test: /\.scss$/,
        exclude: [/node_modules/],
        loader: ExtractTextPlugin.extract("style", "css!postcss!sass?outputStyle=expanded")
      },
      // fonts and svg
      { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&mimetype=application/font-woff" },
      { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&mimetype=application/font-woff" },
      { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&mimetype=application/octet-stream" },
      { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file" },
      { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&mimetype=image/svg+xml" }
    ]
  },
  resolve: {
    // now require('file') instead of require('file.coffee')
    extensions: ['', '.ts', '.webpack.js', '.web.js', '.js', '.json', 'es6', 'png']
  },
  devtool: 'source-map'
};
Run Code Online (Sandbox Code Playgroud)

我的目录结构如下所示

-/
 -server/
 -build/
 -node-modules/
 -public/
  -components/
   -boot/
    -boot.component.ts
   -header/
    -header.component.ts
  -images/
   -logo.png
  -services/
-typings/
 -browser/
 -main/
 -browser.d.ts
 -main.d.ts
-tsconfig.json
-typings.json
Run Code Online (Sandbox Code Playgroud)

我的tsconfig文件如下:

 //tsconfig.json
     {
      "compilerOptions": {
        "target": "es5",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": false,
        "noImplicitAny": false
      },
      "exclude": [
        "node_modules"
      ]
    }
Run Code Online (Sandbox Code Playgroud)

我怀疑我在打字稿编译中弄乱了一些东西,不知道是什么

小智 40

问题是您混淆了TypeScript级别模块和Webpack级别模块.

在Webpack中,您导入的任何文件都会通过某个构建管道.

仅在Typescript中  .ts.js文件是相关的,如果您尝试使用import x from file.pngTypeScript而不知道如何处理它,则TypeScript不会使用Webpack配置.

在您的情况下,您需要分离关注点,import from用于TypeScript/EcmaScript代码并require用于Webpack细节.

您需要在文件中使TypeScript忽略这种特殊的Webpack require语法.d.ts:

declare function require(string): string;
Run Code Online (Sandbox Code Playgroud)

这将使TypeScript忽略require语句,Webpack将能够在构建管道中处理它.


nad*_*dav 19

代替:

import image from 'pathToImage/image.extension';
Run Code Online (Sandbox Code Playgroud)

使用:

const image = require('pathToImage/image.extension');
Run Code Online (Sandbox Code Playgroud)

  • 这有效,它应该是正确的答案。然而,这对我来说就像黑魔法。我不明白如此基本的东西怎么会如此不直观。你是怎么知道这个的? (2认同)

小智 10

我正在使用

import * as myImage from 'path/of/my/image.png';
Run Code Online (Sandbox Code Playgroud)

并用.创建了一个打字稿定义

declare module "*.png" {
    const value: any;
    export = value;
}
Run Code Online (Sandbox Code Playgroud)

这只适用于像webpack中的文件加载器这样的正确处理程序.因为此处理程序将为您提供文件的路径.


Eri*_*ngs 5

对克里斯蒂安·斯托诺夫斯基的答案的一个小改进是使出口默认,即

declare module "*.png" {
  const value: string;
  export default value;
}
Run Code Online (Sandbox Code Playgroud)

因此您可以使用以下方式导入图像:

import myImg from 'img/myImg.png';
Run Code Online (Sandbox Code Playgroud)