Lawrence  Lesch

Lawrence Lesch

1677641280

A TypeScript Language Service Plugin Providing Support for CSS Modules

Typescript-plugin-css-modules

A TypeScript language service plugin for CSS Modules.

typescript-plugin-css-modules example

About this plugin

This plugin provides type information to IDEs and any other tools that work with TypeScript language service plugins.

At this time, TypeScript does not support plugins during compilation. This means that this plugin cannot:

  • provide errors during compilation, or
  • add CSS module support to your project.

For more information, and/or to add support for this feature, see: https://github.com/microsoft/TypeScript/issues/16607.

If you need a different solution, these projects might help:

Installation

To install with Yarn:

yarn add -D typescript-plugin-css-modules

To install with npm:

npm install -D typescript-plugin-css-modules

Once installed, add this plugin to your tsconfig.json:

{
  "compilerOptions": {
    "plugins": [{ "name": "typescript-plugin-css-modules" }]
  }
}

If you're using Visual Studio Code, please also follow these instructions.

As Webpack configurations vary, you may need to provide additional options to this plugin to match your project configuration. For Create React App users, this plugin will work without additional configuration.

Importing CSS

A default export is always provided for your CSS module.

import styles from 'my.module.css';

const a = styles.myClass;
const b = styles['my_other-class'];

As of version 1.1.0, you can also use named exports for classes that don't contain hyphens or underscores. You can still access other classes via the default export.

import styles, { myClass } from 'my.module.css';

const a = myClass;
const b = styles['my_other-class'];

Options

Please note that no options are required. However, depending on your configuration, you may need to customise these options.

OptionDefault valueDescription
additionalDataundefinedAn optional string to append to the top of source files.
allowUnknownClassnamesfalseDisables TypeScript warnings on unknown classnames (for default imports only).
classnameTransform"asIs"See classnameTransform below.
customMatcher"\\.module\\.(c|le|sa|sc)ss$"Changes the file extensions that this plugin processes.
customRendererfalseSee customRenderer below.
customTemplatefalseSee customTemplate below.
goToDefinitionfalseEnables jump to definition. See goToDefinition below.
noUncheckedIndexedAccessfalseEnable for compatibility with TypeScript's noUncheckedIndexedAccess.
namedExportstrueEnables named exports for compatible classnames.
dotenvOptions{}Provides options for dotenv.
postcssOptions{}See postcssOptions below.
rendererOptions{}See rendererOptions below.
{
  "compilerOptions": {
    "plugins": [
      {
        "name": "typescript-plugin-css-modules",
        "options": {
          "classnameTransform": "dashes",
          "customMatcher": "\\.m\\.css$",
          "customRenderer": "./myRenderer.js",
          "dotenvOptions": {},
          "postcssOptions": {},
          "rendererOptions": {}
        }
      }
    ]
  }
}

classnameTransform

Implements the behaviour of the localsConvention css-loader option.

Options available are: 'asIs', 'camelCase', 'camelCaseOnly', 'dashes', and 'dashesOnly'.

customRenderer

The customRenderer is an advanced option, letting you provide the CSS renderer.

When a custom renderer is provided, not other renderers will be used.

The path to the customRenderer must be relative to the project root (i.e. ./myRenderer.js).

The custom renderer itself should be a JavaScript file. The function will be called with three arguments: a css string, an options object (see options.ts), and a compilerOptions object - which contains options as set in your tsconfig.json. It must be synchronous, and must return valid CSS.

module.exports = (css, { fileName, logger }) => {
  try {
    // ...process your css here.
    return renderedCss;
  } catch (error) {
    logger.error(error.message);
  }
};

You can find an example custom renderer in our test fixtures (customRenderer.js).

The internal logger is provided for debugging.

If you use Webpack, note that tilde (~) imports not supported by Less and Sass natively.

For Sass users: A custom importer has been implemented to resolve this as of v3.

For Less users: This package exports a customRenderer that enables tilde imports: less-plugin-aliases.

customTemplate

The customTemplate is an advanced option, letting you provide a template for the generated TypeScript declarations.

When a custom template is provided, its output is used as the virtual declaration (*.d.ts) file.

The path to the customTemplate must be relative to the project root (i.e. ./customTemplate.js).

The custom renderer itself should be a JavaScript file. The function will be called with two arguments: a dts string, and an options object (see options.ts). It must be synchronous, and must return a valid TypeScript declaration (as found in a .d.ts file).

module.exports = (dts, { classes, fileName, logger }) => {
  try {
    // ...generate your template here.
    return customTemplate;
  } catch (error) {
    logger.error(error.message);
  }
};

You can find an example custom template in our test fixtures (customTemplate.js).

The internal logger is provided for debugging.

The classes object represents all the classnames extracted from the CSS Module. They are available if you want to add a custom representation of the CSS classes.

goToDefinition

This allows an editor like Visual Studio Code to go to a classname's definition (file and line).

This is experimental, and may not always work as expected. It currently supports CSS/PostCSS, Less, and Sass. Please raise an issue if you find something isn't working.

postcssOptions

OptionDefault valueDescription
useConfigfalseSet to true to load plugins from your PostCSS config.
excludePluginsfalseOnly sync plugins are supported. Use this to set an array of async plugins to exclude (i.e. ['postcss-mixins'])

rendererOptions

OptionDefault valueDescription
less{}Set renderer options for Less.
sass{}Set renderer options for Sass.
stylus{}Set renderer options for Stylus.

For convenience, loadPaths for Sass are extended, not replaced. The defaults are the path of the current file, and 'node_modules'.

Visual Studio Code

Recommended usage

To use this plugin with Visual Studio Code, you should set your workspace's version of TypeScript, which will load plugins from your tsconfig.json file.

For instructions, see: Using the workspace version of TypeScript.

Alternative usage

If you aren't using any plugin options, you can simple add this plugin to "typescript.tsserver.pluginPaths" in settings. You cannot provide plugin options with this approach.

{
  "typescript.tsserver.pluginPaths": ["typescript-plugin-css-modules"]
}

Custom definitions

Note: Create React App users can skip this section if you're using react-scripts@2.1.x or higher.

If your project doesn't already have global declarations for CSS Modules, you will need to add these to help TypeScript understand the general shape of the imported CSS during build.

Where you store global declarations is up to you. An example might look like: ./src/custom.d.ts.

The below is an example that you can copy or modify (you only declarations for exensions used in your project). If you use a customMatcher, you'll need to modify this.

declare module '*.module.css' {
  const classes: { [key: string]: string };
  export default classes;
}

declare module '*.module.scss' {
  const classes: { [key: string]: string };
  export default classes;
}

declare module '*.module.sass' {
  const classes: { [key: string]: string };
  export default classes;
}

declare module '*.module.less' {
  const classes: { [key: string]: string };
  export default classes;
}

declare module '*.module.styl' {
  const classes: { [key: string]: string };
  export default classes;
}

Troubleshooting

For troubleshooting and debugging, you can view the TypeScript Server Log in Visual Studio Code by entering Typescript: Open TS Server log in the command palette.

If you're not using Visual Studio Code or are having trouble with the above method, you can set the TSS_LOG environment variable.

You can include these logs with any issues you open for this project.

About this project

This project was inspired by a Create React App issue and built on prior work from css-module-types.


Download Details:

Author: mrmckeb
Source Code: https://github.com/mrmckeb/typescript-plugin-css-modules 
License: MIT license

#typescript #plugin #css #modules 

What is GEEK

Buddha Community

A TypeScript Language Service Plugin Providing Support for CSS Modules
Lawrence  Lesch

Lawrence Lesch

1677641280

A TypeScript Language Service Plugin Providing Support for CSS Modules

Typescript-plugin-css-modules

A TypeScript language service plugin for CSS Modules.

typescript-plugin-css-modules example

About this plugin

This plugin provides type information to IDEs and any other tools that work with TypeScript language service plugins.

At this time, TypeScript does not support plugins during compilation. This means that this plugin cannot:

  • provide errors during compilation, or
  • add CSS module support to your project.

For more information, and/or to add support for this feature, see: https://github.com/microsoft/TypeScript/issues/16607.

If you need a different solution, these projects might help:

Installation

To install with Yarn:

yarn add -D typescript-plugin-css-modules

To install with npm:

npm install -D typescript-plugin-css-modules

Once installed, add this plugin to your tsconfig.json:

{
  "compilerOptions": {
    "plugins": [{ "name": "typescript-plugin-css-modules" }]
  }
}

If you're using Visual Studio Code, please also follow these instructions.

As Webpack configurations vary, you may need to provide additional options to this plugin to match your project configuration. For Create React App users, this plugin will work without additional configuration.

Importing CSS

A default export is always provided for your CSS module.

import styles from 'my.module.css';

const a = styles.myClass;
const b = styles['my_other-class'];

As of version 1.1.0, you can also use named exports for classes that don't contain hyphens or underscores. You can still access other classes via the default export.

import styles, { myClass } from 'my.module.css';

const a = myClass;
const b = styles['my_other-class'];

Options

Please note that no options are required. However, depending on your configuration, you may need to customise these options.

OptionDefault valueDescription
additionalDataundefinedAn optional string to append to the top of source files.
allowUnknownClassnamesfalseDisables TypeScript warnings on unknown classnames (for default imports only).
classnameTransform"asIs"See classnameTransform below.
customMatcher"\\.module\\.(c|le|sa|sc)ss$"Changes the file extensions that this plugin processes.
customRendererfalseSee customRenderer below.
customTemplatefalseSee customTemplate below.
goToDefinitionfalseEnables jump to definition. See goToDefinition below.
noUncheckedIndexedAccessfalseEnable for compatibility with TypeScript's noUncheckedIndexedAccess.
namedExportstrueEnables named exports for compatible classnames.
dotenvOptions{}Provides options for dotenv.
postcssOptions{}See postcssOptions below.
rendererOptions{}See rendererOptions below.
{
  "compilerOptions": {
    "plugins": [
      {
        "name": "typescript-plugin-css-modules",
        "options": {
          "classnameTransform": "dashes",
          "customMatcher": "\\.m\\.css$",
          "customRenderer": "./myRenderer.js",
          "dotenvOptions": {},
          "postcssOptions": {},
          "rendererOptions": {}
        }
      }
    ]
  }
}

classnameTransform

Implements the behaviour of the localsConvention css-loader option.

Options available are: 'asIs', 'camelCase', 'camelCaseOnly', 'dashes', and 'dashesOnly'.

customRenderer

The customRenderer is an advanced option, letting you provide the CSS renderer.

When a custom renderer is provided, not other renderers will be used.

The path to the customRenderer must be relative to the project root (i.e. ./myRenderer.js).

The custom renderer itself should be a JavaScript file. The function will be called with three arguments: a css string, an options object (see options.ts), and a compilerOptions object - which contains options as set in your tsconfig.json. It must be synchronous, and must return valid CSS.

module.exports = (css, { fileName, logger }) => {
  try {
    // ...process your css here.
    return renderedCss;
  } catch (error) {
    logger.error(error.message);
  }
};

You can find an example custom renderer in our test fixtures (customRenderer.js).

The internal logger is provided for debugging.

If you use Webpack, note that tilde (~) imports not supported by Less and Sass natively.

For Sass users: A custom importer has been implemented to resolve this as of v3.

For Less users: This package exports a customRenderer that enables tilde imports: less-plugin-aliases.

customTemplate

The customTemplate is an advanced option, letting you provide a template for the generated TypeScript declarations.

When a custom template is provided, its output is used as the virtual declaration (*.d.ts) file.

The path to the customTemplate must be relative to the project root (i.e. ./customTemplate.js).

The custom renderer itself should be a JavaScript file. The function will be called with two arguments: a dts string, and an options object (see options.ts). It must be synchronous, and must return a valid TypeScript declaration (as found in a .d.ts file).

module.exports = (dts, { classes, fileName, logger }) => {
  try {
    // ...generate your template here.
    return customTemplate;
  } catch (error) {
    logger.error(error.message);
  }
};

You can find an example custom template in our test fixtures (customTemplate.js).

The internal logger is provided for debugging.

The classes object represents all the classnames extracted from the CSS Module. They are available if you want to add a custom representation of the CSS classes.

goToDefinition

This allows an editor like Visual Studio Code to go to a classname's definition (file and line).

This is experimental, and may not always work as expected. It currently supports CSS/PostCSS, Less, and Sass. Please raise an issue if you find something isn't working.

postcssOptions

OptionDefault valueDescription
useConfigfalseSet to true to load plugins from your PostCSS config.
excludePluginsfalseOnly sync plugins are supported. Use this to set an array of async plugins to exclude (i.e. ['postcss-mixins'])

rendererOptions

OptionDefault valueDescription
less{}Set renderer options for Less.
sass{}Set renderer options for Sass.
stylus{}Set renderer options for Stylus.

For convenience, loadPaths for Sass are extended, not replaced. The defaults are the path of the current file, and 'node_modules'.

Visual Studio Code

Recommended usage

To use this plugin with Visual Studio Code, you should set your workspace's version of TypeScript, which will load plugins from your tsconfig.json file.

For instructions, see: Using the workspace version of TypeScript.

Alternative usage

If you aren't using any plugin options, you can simple add this plugin to "typescript.tsserver.pluginPaths" in settings. You cannot provide plugin options with this approach.

{
  "typescript.tsserver.pluginPaths": ["typescript-plugin-css-modules"]
}

Custom definitions

Note: Create React App users can skip this section if you're using react-scripts@2.1.x or higher.

If your project doesn't already have global declarations for CSS Modules, you will need to add these to help TypeScript understand the general shape of the imported CSS during build.

Where you store global declarations is up to you. An example might look like: ./src/custom.d.ts.

The below is an example that you can copy or modify (you only declarations for exensions used in your project). If you use a customMatcher, you'll need to modify this.

declare module '*.module.css' {
  const classes: { [key: string]: string };
  export default classes;
}

declare module '*.module.scss' {
  const classes: { [key: string]: string };
  export default classes;
}

declare module '*.module.sass' {
  const classes: { [key: string]: string };
  export default classes;
}

declare module '*.module.less' {
  const classes: { [key: string]: string };
  export default classes;
}

declare module '*.module.styl' {
  const classes: { [key: string]: string };
  export default classes;
}

Troubleshooting

For troubleshooting and debugging, you can view the TypeScript Server Log in Visual Studio Code by entering Typescript: Open TS Server log in the command palette.

If you're not using Visual Studio Code or are having trouble with the above method, you can set the TSS_LOG environment variable.

You can include these logs with any issues you open for this project.

About this project

This project was inspired by a Create React App issue and built on prior work from css-module-types.


Download Details:

Author: mrmckeb
Source Code: https://github.com/mrmckeb/typescript-plugin-css-modules 
License: MIT license

#typescript #plugin #css #modules 

Hire CSS Developer

Want to develop a website or re-design using CSS Development?

We build a website and we implemented CSS successfully if you are planning to Hire CSS Developer from HourlyDeveloper.io, We can fill your Page with creative colors and attractive Designs. We provide services in Web Designing, Website Redesigning and etc.

For more details…!!
Consult with our experts:- https://bit.ly/3hUdppS

#hire css developer #css development company #css development services #css development #css developer #css

Rahim Makhani

Rahim Makhani

1618806778

Get the best Magento maintenance service for your e-commerce store

Magento is the most demanded technology for developing online eCommerce stores and Magento service is important for better working of the online store. Nevina Infotech provides you with Magento maintenance and services.

Magento maintenance is the process of checking the performance of the website and checking the regular updates, backups, online store management, and much more.

You can choose Nevina Infotech for Magento maintenance service for your eCommerce store. We provide the best Magento support and maintenance for eCommerce stores.

#magento maintenance and support services #magento support services #magento support and maintenance #magento support #magento maintenance support #magento technical support

Zed Care

1620197224

NDIS Service Provider | Registered NDIS Providers in Sydney - ZedCare

ZedCare Ability Services is an NDIS service provider committed to improving the lives of our clients. By assisting the elderly, people with disability and NDIS participants with their daily living activities, we can keep them at home where they are comfortable and allow them to thrive during their transitional phases in life. Not only do we pioneer in exceeding client’s satisfaction, but we also strive to exceed employee satisfaction as well. This is what motivates us to provide the best health care in Sydney & its suburbs.

#ndis service provider #disability care services #disability support provider #supported independent living

The Definitive Guide to TypeScript & Possibly The Best TypeScript Book

TypeScript Deep Dive

I've been looking at the issues that turn up commonly when people start using TypeScript. This is based on the lessons from Stack Overflow / DefinitelyTyped and general engagement with the TypeScript community. You can follow for updates and don't forget to ★ on GitHub 🌹

Reviews

  • Thanks for the wonderful book. Learned a lot from it. (link)
  • Its probably the Best TypeScript book out there. Good Job (link)
  • Love how precise and clear the examples and explanations are! (link)
  • For the low, low price of free, you get pages of pure awesomeness. Chock full of source code examples and clear, concise explanations, TypeScript Deep Dive will help you learn TypeScript development. (link)
  • Just a big thank you! Best TypeScript 2 detailed explanation! (link)
  • This gitbook got my project going pronto. Fluent easy read 5 stars. (link)
  • I recommend the online #typescript book by @basarat you'll love it.(link)
  • I've always found this by @basarat really helpful. (link)
  • We must highlight TypeScript Deep Dive, an open source book.(link)
  • Great online resource for learning. (link)
  • Thank you for putting this book together, and for all your hard work within the TypeScript community. (link)
  • TypeScript Deep Dive is one of the best technical texts I've read in a while. (link)
  • Thanks @basarat for the TypeScript Deep Dive Book. Help me a lot with my first TypeScript project. (link)
  • Thanks to @basarat for this great #typescript learning resource. (link)
  • Guyz excellent book on Typescript(@typescriptlang) by @basarat (link)
  • Leaning on the legendary @basarat's "TypeScript Deep Dive" book heavily at the moment (link)
  • numTimesPointedPeopleToBasaratsTypeScriptBook++; (link)
  • A book not only for typescript, a good one for deeper JavaScript knowledge as well. link
  • In my new job, we're using @typescriptlang, which I am new to. This is insanely helpful huge thanks, @basarat! link
  • Thank you for writing TypeScript Deep Dive. I have learned so much. link
  • Loving @basarat's @typescriptlang online book basarat.gitbooks.io/typescript/# loaded with great recipes! link
  • Microsoft doc is great already, but if want to "dig deeper" into TypeScript I find this book of great value link
  • Thanks, this is a great book 🤓🤓 link
  • Deep dive to typescript is awesome in so many levels. i find it very insightful. Thanks link
  • @basarat's intro to @typescriptlang is still one of the best going (if not THE best) link
  •  
  • This is sweet! So many #typescript goodies! link

Get Started

If you are here to read the book online get started.

Translations

Book is completely free so you can copy paste whatever you want without requiring permission. If you have a translation you want me to link here. Send a PR.

Other Options

You can also download one of the Epub, Mobi, or PDF formats from the actions tab by clicking on the latest build run. You will find the files in the artifacts section.

Special Thanks

All the amazing contributors 🌹

Share

Share URL: https://basarat.gitbook.io/typescript/

Author: Basarat
Source Code: https://github.com/basarat/typescript-book/ 
License: View license

#typescript #opensource