在webpack中使用带有es6模块和typescript的文件加载器

时间:2015-11-25 11:57:18

标签: typescript webpack

webpack.config.js

resolveLoader: { 
    alias: {
        'copy': 'file-loader?name=[path][name].[ext]&context=./src',
    }
},

当我使用javascript时,这有效:

entry.js

 var index = require("copy!../src/index.html");

但我已经使用(ts-loader)移动到打字稿了,所以我稍微修改了我在entry.ts中所做的事情:

import * as index from 'copy!index.html';

但现在这给了我一个错误:

ERROR in ./src/entry.ts
(3,24): error TS2307: Cannot find module 'copy!../src/index.html'.

3 个答案:

答案 0 :(得分:8)

使用TypeScript 2,您可以使用通配符模块声明:

declare module "*!text" {
    const content: string;
    export default content;
}
// Some do it the other way around.
declare module "json!*" {
    const value: any;
    export default value;
}

现在您可以导入与“*!text”或“json!*”匹配的内容。

import fileContent from "./xyz.txt!text";
import data from "json!http://example.com/data.json";
console.log(data, fileContent);

答案 1 :(得分:4)

alex's answer非常棒,非常灵活。

我遇到an alternative更具体的文件类型,因此它不太灵活,但不需要前缀/后缀。

  1. 使用declare module '*.png'
  2. 创建文件
  3. 使用import * as logo from "./ss-logo-transparent.png";
  4. 导入

答案 2 :(得分:3)

  

找不到模块'copy!../ src / index.html'。

必须声明不是用TypeScript编写的外部模块。

快速修复

只需使用此处定义的declare var require: { <T>(path: string): T; (paths: string[], callback: (...modules: any[]) => void): void; ensure: ( paths: string[], callback: (require: <T>(path: string) => T) => void ) => void; }; 函数:https://github.com/TypeStrong/ts-loader#code-splitting-and-loading-other-resources

代码:

inline-block
相关问题