Daniel Gaeta Daniel Gaeta - 4 days ago 6
TypeScript Question

typescript compiler option for resolving scss imports

I am using the following compiler options for a tool I am making and I am seeing an error when the compiler can't find the compiled scss file.

In other words, I have the following files:


  • ClassA.tsx


    • This file has the line:
      import styles from './ClassA.module.scss';


  • ClassA.module.scss



After the files are compiled I have the files:


  • ClassA.js


    • This file has the line:
      var ClassA_module_scss_1 = require('./ClassA.module.scss');


  • Class.module.scss.js



And I am seeing the error:
Cannot find module ClassA.module.scss


These are my compiler options:

compilerOptions: {
target: typescript.ScriptTarget.ES5,
module: typescript.ModuleKind.CommonJS,
moduleResolution: typescript.ModuleResolutionKind.NodeJs,
rootDir: this.buildConfig.rootPath,
declaration: true,
experimentalDecorators: true,
jsx: typescript.JsxEmit.React,
sourceMap: true
}


Is there something special I must do to resolve the scss file?

Answer

Importing assets or stylesheets is not a feature supported by TypeScript itself. For this to work, you need some module bundler that is aware of non-typescript/javascript imports like images or scss files. Webpack is such a tool that handles imports of assets and can do much more for you.

http://webpack.github.io/

When integrating webpack, you need the corresponding loaders to enable support for scss. You can find more details on configuring it to enable this at sass-loader docs. Before you should definitely have a look at the webpack docs to get a general understanding of how webpack and the loaders work. This can be somehow confusing in the beginning.

Please be aware that currently version 2 of webpack is still in development and you may encounter some tutorials that don't work for version 1.

Comments