webpack 无法导入图像(在打字稿中使用 express 和 angular2) [英] webpack not able to import images( using express and angular2 in typescript)

查看:30
本文介绍了webpack 无法导入图像(在打字稿中使用 express 和 angular2)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在 headercomponent.ts 中导入图像.我怀疑这是因为我在编译 ts 时做错了(使用 webpack ts 加载器),因为同样的事情适用于 react(组件是用 es6 编写的)

错误位置是

//headercomponent.ts从angular2/core"导入 {Component, View};从angular2/router"导入{ROUTER_DIRECTIVES, Router};从../../services/auth/auth.service"导入{AuthService};从../../images/logo.png"导入 logoSource;//**这会导致错误** 找不到模块../../images/logo.png"@零件({选择器:'我的标题',//templateUrl:'components/header/header.tmpl.html' ,模板:`<header class="main-header"><div class="top-bar"><div class="top-bar-title"><a href="/"><img src="{{logoSource}}"></a>

我的 webpack 配置是

//webpack.config.js'使用严格';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)模块.出口 = {条目:path.join(basePath,'/components/boot/boot.ts'),输出: {path: path.join(basePath,"..","/build"),//这是图像和 js 的去处publicPath: path.join(basePath,"..","/build/assets"),//publicPath: path.join(basePath ,'/images'),//这用于生成 URL,例如图片文件名:'bundle.js'},插件: [新的 ExtractTextPlugin("bundle.css")],模块: {预加载器: [ { 测试:/.tsx$/, 加载器: "tslint" } ],//装载机: [{ test:/.(png!jpg)$/, loader: 'file-loader?name=/img/[name].[ext]' },//内联 base64 用于 <=8k 图像,直接 URL 用于其余的部分{测试:/.json/,装载机:'json-装载机',},{测试:/.ts$/,loader: 'ts-loader',排除:[/node_modules/]},{测试:/.js$/,loader: 'babel-loader'},{测试:/.scss$/,排除:[/node_modules/],loader: ExtractTextPlugin.extract("style", "css!postcss!sass?outputStyle=expanded")},//字体和 svg{ test:/.woff(?v=d+.d+.d+)?$/, loader: "url-loader?limit=10000&mimetype=application/font-woff" },{ 测试:/.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" },{ 测试:/.svg(?v=d+.d+.d+)?$/, loader: "url-loader?limit=10000&mimetype=image/svg+xml" }]},解决: {//现在 require('file') 而不是 require('file.coffee')扩展名:['', '.ts', '.webpack.js', '.web.js', '.js', '.json', 'es6', 'png']},开发工具:'源地图'};

我的目录结构是这样的

-/-服务器/-建造/-节点模块/-上市/-组件/-引导/-boot.component.ts-标题/-header.component.ts-图片/-logo.png-服务/-打字/-浏览器/-主要的/-browser.d.ts-main.d.ts-tsconfig.json-typings.json

我的tsconfig文件如下:

//tsconfig.json{编译器选项":{目标":es5",源地图":真,emitDecoratorMetadata":真,"experimentalDecorators": 真,删除评论":假,"noImplicitAny": 假},排除": [节点模块"]}

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

解决方案

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

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

在 Typescript 中,只有 .ts.js 文件是相关的,如果你尝试 import x from file.png TypeScript 只是没有知道如何处理它,TypeScript 不使用 Webpack 配置.

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

你需要让 TypeScript 忽略这个特殊的 Webpack require 语法,在 .d.ts 文件中定义如下:

声明函数 require(string): string;

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

I am not able to import images in my headercomponent.ts. I suspect it is because of something i am doing wrong while compiling ts(using webpack ts loader) because same thing works with react( where the components are written in es6)

The error location is

//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>

my webpack config is

// 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'
};

and my directory structure looks like this

-/
 -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

my tsconfig file is as follows:

 //tsconfig.json
     {
      "compilerOptions": {
        "target": "es5",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": false,
        "noImplicitAny": false
      },
      "exclude": [
        "node_modules"
      ]
    }

I suspect I am messing some thing in typescript compilation , not sure what

解决方案

The problem is that you confuse TypeScript level modules and Webpack level modules.

In Webpack any file that you import goes through some build pipeline.

In Typescript only .ts and .js files are relevant and if you try to import x from file.png TypeScript just does not know what to do with it, Webpack config is not used by TypeScript.

In your case you need to separate the concerns, use import from for TypeScript/EcmaScript code and use require for Webpack specifics.

You would need to make TypeScript ignore this special Webpack require syntax with a definition like this in a .d.ts file:

declare function require(string): string;

This will make TypeScript ignore the require statements and Webpack will be able to process it in the build pipeline.

这篇关于webpack 无法导入图像(在打字稿中使用 express 和 angular2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆