Webpack: imports the TypeScript module as "normal" as well as as raw string

Using webpack ^v2.2.1 , I would like to import the TypeScript module as text, in addition to importing the same module normally.

I realized that I should probably use raw-loader . But it does not work.

Code example:

 import DemoComponent from './demo' import demoCode from 'raw-loader!./demo' 

TypeScript yells at me something like

 error TS2307: Cannot find module 'raw-loader!./demo'. 

I am using ts-loader .

Here is my webpack.config.js :

 const { resolve } = require('path') const fail = require('webpack-fail-plugin') const config = { entry: './docs/index.ts', output: { filename: 'bundle.js', path: resolve(__dirname, 'docs-build') }, resolve: { extensions: [ '.ts', '.js' ] }, devtool: 'inline-source-map', module: { rules: [ { enforce: 'pre', test: /\.js$/, loader: 'source-map-loader' }, { test: /\.ts$/, loader: 'ts-loader' }, { test: /\.scss$/, use: [ 'style-loader', { loader: 'css-loader', options: { sourceMap: true } }, 'sass-loader' ] } ] }, plugins: [ fail ] } module.exports = config 
+8
source share
3 answers

In case someone is looking for a solution to this answer. Using import is the best option - it will be typed and will allow you to optimize module packages, such as Rollup and Webpack 3+, when import vs require output:

You need to create raw-loader.d.ts and make sure it is included in your tsconfig.json file. Enter the following content:

 declare module '!!raw-loader!*' { const contents: string export = contents } 

tsconfig.json :

 { "compilerOptions": { "types": ["raw-loader.d.ts", "node"] } } 
+6
source

The following seems to work:

 import DemoComponent from './demo' const demoCode = require('!!raw-loader!./demo') 

But I'm not sure how right this is. I would like to find documentation on the order and mechanism of loaders.

In addition, I would prefer to be consistent, using import statements instead. But TypeScript complains about this if I do a direct conversion:

 import DemoComponent from './demo' import demoCode from '!!raw-loader!./demo' 

Error is simple

 error TS2307: Cannot find module '!!raw-loader!./demo'. 
+2
source

For your mistake:

raw-loader.d.ts :

 declare module '!!raw-loader!*' { const contents: string export default contents } 
0
source

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


All Articles