簡體   English   中英

使用`import`語句從帶有webpack的打字稿中導入原始文件

[英]Import raw files from typescript with webpack using the `import` statement

我需要使用webpack從打字稿中導入原始數據。 這是我的設置:

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

file.txt的

file-content

main.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時,它說找不到模塊:

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

我的問題是:如何將txt數據導入打字稿文件? 例如,這在編寫角度組件並導入html模板以將其分配給該組件的template屬性時很有用。

所以我終於讓它工作了。 我在.d.ts文件中添加了模塊聲明:

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

然后只有我這樣導入.txt文件:

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

您可以在這里找到更多關於此的信息

編輯:

如果要使用import關鍵字,請按以下方式使用它:

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

我在src根目錄中添加了一個全局定義文件global.d.ts並添加:

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

我不需要任何額外的tsconfig.json ,而我對raw-loader有了標准的webpack規則:

rules: [
   {
      test: /\.txt$/i,
      loader: 'raw-loader',
   },

然后,我可以將一個名為./source.js.txt的純文本文件導入ts變量,如下所示:

import txt from './source.js.txt'

這似乎與讓TS開心而不是讓Webpack更加相關。 關鍵似乎是模塊定義。 全局或每個文件(如果需要)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM