Using file loader with es6 and typescript modules in webpack

webpack.config.js :

 resolveLoader: { alias: { 'copy': 'file-loader?name=[path][name].[ext]&context=./src', } }, 

When I used javascript, it worked:

entry.js :

  var index = require("copy!../src/index.html"); 

But I moved to typescript using (ts-loader), so I changed a bit what I did in entry.ts :

 import * as index from 'copy!index.html'; 

but now it gives me an error:

 ERROR in ./src/entry.ts (3,24): error TS2307: Cannot find module 'copy!../src/index.html'. 
+3
source share
3 answers

Cannot find module 'copy! ../ src / index.html'.

External modules not written to TypeScript must be declared.

Quick fix

just use the require function as defined here: https://github.com/TypeStrong/ts-loader#code-splitting-and-loading-other-resources

Code:

 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; }; 
+3
source

With TypeScript 2, you can have wildcard declarations:

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

Now you can import things that match "*! Text" or "json! *".

 import fileContent from "./xyz.txt!text"; import data from "json!http://example.com/data.json"; console.log(data, fileContent); 
+6
source

alex's answer is excellent and very flexible.

I came across an alternative that is more specific to the file type, so it is less flexible, but does not require prefixes / suffixes.

  • Create a file with declare module '*.png'
  • Import with import * as logo from "./ss-logo-transparent.png";
+3
source

Source: https://habr.com/ru/post/1265103/


All Articles