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

Ash*_*man 5 typescript webpack

webpack.config.js:

resolveLoader: { 
    alias: {
        'copy': 'file-loader?name=[path][name].[ext]&context=./src',
    }
},
Run Code Online (Sandbox Code Playgroud)

当我使用javascript时,这工作:

entry.js:

 var index = require("copy!../src/index.html");
Run Code Online (Sandbox Code Playgroud)

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

import * as index from 'copy!index.html';
Run Code Online (Sandbox Code Playgroud)

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

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

ale*_*lex 9

使用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;
}
Run Code Online (Sandbox Code Playgroud)

现在您可以导入与"*!text"或"json!*"匹配的内容.

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

  • 我在哪里放置这些通配符模块声明? (4认同)
  • 当我使用此技术时,我无法获得丢失文件的编译时错误。例如,我可以执行 `import TotalFake from './totally/fake/file.txt';`,并且我的带有 TS 的 React 应用程序将编译没有问题,尽管该文件不存在。这意味着我的情况并不比我只是将文件放在“/public”目录中并使用“<a href='/path/to/file.txt'></a>”更好。有人知道如何让这些导入以一种让 TS 满意的方式工作,并确保文件存在吗? (2认同)

小智 5

亚历克斯的答案是一个很好的答案,而且非常灵活。

我遇到了一个更特定于文件类型的替代方法,因此它的灵活性较差,但不需要前缀/后缀。

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

  • 当我使用此技术时,我无法获得丢失文件的编译时错误。例如,我可以从'./totally/fake/file.txt'导入totallyFake;,并且我的React应用程序与TS将编译没有问题,尽管该文件不存在。这意味着我的情况并不比直接将文件放入 /public 目录并使用 <a href='/path/to/file.txt'></a> 更好。有人知道如何让这些导入以一种让 TS 满意的方式工作,并确保文件存在吗? (2认同)

bas*_*rat 3

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

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

快速解决

只需使用require此处定义的函数:https://github.com/TypeStrong/ts-loader#code-splitting-and-loading-other-resources

代码:

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;
};
Run Code Online (Sandbox Code Playgroud)