在 webpack 中使用带有 es6 模块和 typescript 的文件加载器
Using file-loader with es6 modules and typescript in 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'.
Cannot find module '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;
};
使用 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);
很棒,而且非常灵活。
我遇到了 an alternative,它更特定于文件类型,因此不太灵活,但不需要 prefixes/suffixes。
- 使用
declare module '*.png'
创建一个文件
- 使用
import * as logo from "./ss-logo-transparent.png";
导入
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'.
Cannot find module '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;
};
使用 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);
我遇到了 an alternative,它更特定于文件类型,因此不太灵活,但不需要 prefixes/suffixes。
- 使用
declare module '*.png'
创建一个文件
- 使用
import * as logo from "./ss-logo-transparent.png";
导入