Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A TypeScript language service plugin providing support for CSS Modules.

License

NotificationsYou must be signed in to change notification settings

mrmckeb/typescript-plugin-css-modules

Repository files navigation

npmnpmlicense

ATypeScript language service pluginforCSS Modules.

typescript-plugin-css-modules example

Table of contents

About this plugin

This plugin provides type information to IDEs and any other tools that work withTypeScript 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:microsoft/TypeScript#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 yourtsconfig.json:

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

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

As Webpack configurations vary, you may need to provide additionaloptions 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.

importstylesfrom'my.module.css';consta=styles.myClass;constb=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.

importstyles,{myClass}from'my.module.css';consta=myClass;constb=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"SeeclassnameTransform below.
customMatcher"\\.module\\.(c|le|sa|sc)ss$"Changes the file extensions that this plugin processes.
customRendererfalseSeecustomRenderer below.
customTemplatefalseSeecustomTemplate below.
goToDefinitionfalseEnables jump to definition. SeegoToDefinition below.
noUncheckedIndexedAccessfalseEnable for compatibility with TypeScript'snoUncheckedIndexedAccess.
namedExportstrueEnables named exports for compatible classnames.
dotenvOptions{}Provides options fordotenv.
postcssOptions{}SeepostcssOptions below.
rendererOptions{}SeerendererOptions 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 thelocalsConventioncss-loader option.

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

customRenderer

ThecustomRenderer 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 thecustomRenderer 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: acss string, anoptions object (seeoptions.ts), and acompilerOptions object - which contains options as set in yourtsconfig.json. It must be synchronous, and must return valid CSS.

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

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

Theinternallogger is provided fordebugging.

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

ThecustomTemplate 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 thecustomTemplate 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: adts string, and anoptions object (seeoptions.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.returncustomTemplate;}catch(error){logger.error(error.message);}};

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

Theinternallogger is provided fordebugging.

Theclasses 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 totrue to load plugins from yourPostCSS 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{}Setrenderer options for Less.
sass{}Setrenderer options for Sass.
stylus{}Setrenderer 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 yourtsconfig.json file.

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

Alternative usage

If you aren't using anyplugin 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 usingreact-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 acustomMatcher, you'll need to modify this.

declare module'*.module.css'{constclasses:{[key:string]:string};exportdefaultclasses;}declare module'*.module.scss'{constclasses:{[key:string]:string};exportdefaultclasses;}declare module'*.module.sass'{constclasses:{[key:string]:string};exportdefaultclasses;}declare module'*.module.less'{constclasses:{[key:string]:string};exportdefaultclasses;}declare module'*.module.styl'{constclasses:{[key:string]:string};exportdefaultclasses;}

Troubleshooting

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

If you're not using Visual Studio Code or are having trouble with the above method, you can set theTSS_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 Appissueand built on prior work fromcss-module-types.

About

A TypeScript language service plugin providing support for CSS Modules.

Topics

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp