How do I reference CSS style files in TSDX?

Use scaffolding to quickly develop the React component NPM package (based on TSDX)

TSDX does not support the import of CSS by default.

* Failed to compile Error: Unexpected Token (Note that you need plugins to import files that are not JavaScript)Copy the code

The solution

In the project root directory, create tsdx.config.js:

const postcss = require('rollup-plugin-postcss');

module.exports = {
  rollup(config, options) {
    config.plugins.push(
      postcss({
        inject: false.extract:!!!!! options.writeMeta, }), );returnconfig; }};Copy the code

And install this plugin:

npm i -D rollup-plugin-postcss
Copy the code

Tsdx.config. js is used to modify the rollup configuration of TSDX (TSDX is based on rollup encapsulation, through this file exposed interface, we can directly modify the rollup configuration). Rollup-plugin-postcss is a rollup plugin that allows you to use CSS.

The effect

After importing ‘xxx. CSS ‘from the project, TSDX will find this sentence and package it, and you will see the file xxx.cjs.development. CSS in the dist folder as the output CSS file.

Note: this will only pack CSS files, how will users of your NPM package refer to them?

We are developing NPM packages, and it is best to let users decide when to reference styles! So when users use it, they need to quote our CSS file in a single sentence:

import 'xxx/xxx.cjs.development.css'
Copy the code

Of course, if you think that your NPM package, users must import CSS, you can also actively “inject CSS” method, the advantage is that users do not need to manually import CSS files, how to do? Inject: true by modifying a configuration in tsdx.config.js.

const postcss = require('rollup-plugin-postcss');

module.exports = {
  rollup(config, options) {
    config.plugins.push(
      postcss({
        inject: true.// change this to true
        extract:!!!!! options.writeMeta, }), );returnconfig; }};Copy the code

Dist /xxx.esm.js, which is imported via ESM, adds styleInject:

function styleInject(css, ref) {
  if ( ref === void 0 ) ref = {};
  var insertAt = ref.insertAt;

  if(! css ||typeof document= = ='undefined') { return; }

  var head = document.head || document.getElementsByTagName('head') [0];
  var style = document.createElement('style');
  style.type = 'text/css';

  if (insertAt === 'top') {
    if (head.firstChild) {
      head.insertBefore(style, head.firstChild);
    } else{ head.appendChild(style); }}else {
    head.appendChild(style);
  }

  if (style.styleSheet) {
    style.styleSheet.cssText = css;
  } else {
    style.appendChild(document.createTextNode(css)); }}// ...
// This will be called below
var css_28z = ".test-module_card__1YX84{background:#0ff; color:#7fffd4}";
styleInject(css_248z);
Copy the code

This function simply generates a

So users of your NPM package don’t need to import CSS files themselves, they have styles too!