Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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;

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'.

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.

like image 254
Luke Skywalker Avatar asked Nov 05 '17 14:11

Luke Skywalker


2 Answers

I added a global definition file global.d.ts in src root and added:

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

I didn't need any extra tsconfig.json, and I just had the standard webpack rule for raw-loader:

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

Then I could import a plain text file called ./source.js.txt into ts variable like this:

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

It seemed more to do with making TS happy than webpack. The key seems to be the module definition. Either global or per file if needed.

like image 137
Ali Avatar answered Sep 23 '22 22:09

Ali


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;
}

And only then I imported .txt file like this:

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

You can find more about this here.

EDIT:

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

import * as someTextContent from './some.txt';
like image 21
Kacper Wiszczuk Avatar answered Sep 22 '22 22:09

Kacper Wiszczuk