【问题标题】:Using file-loader with es6 modules and typescript in webpack在 webpack 中使用带有 es6 模块和 typescript 的文件加载器
【发布时间】:2016-02-28 05:00:51
【问题描述】:

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) 转移到 typescript,所以我稍微修改了我在 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'.

【问题讨论】:

    标签: typescript webpack


    【解决方案1】:

    使用 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);
    

    【讨论】:

    • 我在哪里放置这些通配符模块声明?
    • 将它放在一个名为 index.d.ts 的文件中对我有用。不确定模块声明是否也可以放置到其他位置。
    • 当我使用这种技术时,我无法获得丢失文件的编译时错误。例如,我可以执行import totallyFake from './totally/fake/file.txt';,并且我的带有 TS 的 React 应用程序将编译没有问题,尽管该文件不存在。这意味着我不会比我只是将文件放在/public 目录中并使用<a href='/path/to/file.txt'></a> 更好。任何人都知道如何让这些导入以让 TS 满意的方式工作,并确保文件存在?
    【解决方案2】:

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

    我遇到了an alternative,它更特定于文件类型,因此不太灵活,但不需要前缀/后缀。

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

    【讨论】:

    • 当我使用这种技术时,我无法获得丢失文件的编译时错误。例如,我可以从 './totally/fake/file.txt' 导入完全伪造;并且我的带有 TS 的 React 应用程序将编译没有问题,尽管该文件不存在。这意味着我不会比我只是将文件放在 /public 目录中并使用 更好。任何人都知道如何让这些导入以一种让 TS 满意的方式工作,并确保文件存在?
    【解决方案3】:

    找不到模块“复制!../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;
    };
    

    【讨论】:

    • @AndyJ 固定链接并从链接中添加内容
    猜你喜欢
    • 2017-03-13
    • 2016-10-28
    • 2016-02-26
    • 2018-01-06
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    • 2017-12-09
    相关资源
    最近更新 更多