使用 `import` 语句从带有 webpack 的打字稿导入原始文件 [英] Import raw files from typescript with webpack using the `import` statement

查看:42
本文介绍了使用 `import` 语句从带有 webpack 的打字稿导入原始文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 webpack 从打字稿导入原始数据.这是我的设置:

I need to import raw data from typescript using webpack. Here is my setup:

$ tree
.
+-- file.txt
+-- main.ts
+-- package.json
+-- tsconfig.json
+-- webpack.config.js

file.txt

file-content

ma​​in.js

import file from './file.txt';

console.log(file);

package.json

{
  "devDependencies": {
    "raw-loader": "^0.5.1",
    "ts-loader": "^3.1.1",
    "typescript": "^2.6.1",
    "webpack": "^3.8.1"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es5",
    "baseUrl": "app"
  },
  "exclude": [
    "node_modules"
  ]
}

webpack.config.js

const path = require('path');

const config = {
  entry: './main.ts',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'app.js'
  },
  module: {
    rules: [
      { test: /\.txt$/, use: 'raw-loader' },
      { test: /\.tsx?$/, loader: 'ts-loader' },
    ]
  }
};

module.exports = config;

当我运行 weback 时,它说找不到模块:

when I run weback, it says it can't find the module:

ERROR in ./main.ts
[tsl] ERROR in /tmp/test/main.ts(1,18)
      TS2307: Cannot find module './file.txt'.

我的问题是:如何将 txt 数据导入打字稿文件?例如,在编写 angular 组件并导入 html 模板以将其分配给该组件的模板属性时,这很有用.

My question is: How can I import txt data into a typescript file? This is useful when writing an angular component, for example, and importing an html template to assign it to the template property of that component.

推荐答案

所以我终于让它工作了.我在 .d.ts 文件中添加了模块声明:

So I finally got it to work. I have added module declaration in .d.ts file:

declare module '*.txt' {
  const content: any;
  export default content;
}

然后我才像这样导入了 .txt 文件:

And only then I imported .txt file like this:

const someTextContent = require('./some.txt');

您可以在此处找到更多相关信息.

You can find more about this here.

如果您想使用 import 关键字,请按如下方式使用:

If you want to use import keyword just use it as following:

import * as someTextContent from './some.txt';

这篇关于使用 `import` 语句从带有 webpack 的打字稿导入原始文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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