jaredpalmer / tsdx

Zero-config CLI for TypeScript package development
https://tsdx.io
MIT License
11.24k stars 506 forks source link

HOWTOs #379

Open ambroseus opened 4 years ago

ambroseus commented 4 years ago

Collection of useful HOWTOs

:warning: Warning

These modifications will override the default behavior and configuration of TSDX. As such they can invalidate internal guarantees and assumptions. These types of changes can break internal behavior and can be very fragile against updates. Use with discretion!

ambroseus commented 4 years ago

How to correctly transpile spread on iterables (Set, Map) https://github.com/jaredpalmer/tsdx/issues/376

tsconfig.json

  "downlevelIteration": true

package.json

{
  "scripts":
    {
       "build": "tsdx build --target node"
    }
}
ambroseus commented 4 years ago

How to change output folder name from "dist" to "build" https://github.com/jaredpalmer/tsdx/issues/351

tsdx.config.js

module.exports = {
  rollup(config, options) {
    config.output.file = config.output.file.replace('dist', 'build');

    return config;
  },
};
ambroseus commented 4 years ago

How to 'play nicely' with tsdx + VS Code + eslint https://github.com/jaredpalmer/tsdx/issues/354

https://github.com/jaredpalmer/tsdx#npm-run-lint-or-yarn-lint run npm run lint --write-file or yarn lint --write-file to generate .eslintrc.js file

swyxio commented 4 years ago

nice. worth adding to docs when you think its ready.

ambroseus commented 4 years ago

@sw-yx yep) can you plz add label documentation for this issue?

nartc commented 4 years ago

How to setup Example app with live reload for React Native

Note: This is a hack, rather than a solution. This hack requires the example app to be in Javascript instead of TypeScript to prevent additional configuration needed.

  1. Init a react-native app using your favorite CLI. (I use ReactNative CLI) in the root dir of the library (aka example should stay on the same level of src)
  2. Create tsdx.config.js in the root dir if you haven't already
  3. Overide TSDX config with the following:
module.exports = {
   rollup(config, options) {
      const { localDev, name } = options; // localDev can be whatever name you want
      if (localDev) {
          config.output.file = config.output.file.replace('dist', `example/${name}`);
          return config;
      }
      return config;
   }
}
  1. Setup a script in package.json
{
   ...
   scripts: {
      "watch": "tsdx watch",
      "dev": "tsdx watch --localDev", // <-- add this line, localDev is just a property name
   }
}

image PS: Even though the example app is in JS, type definitions output from tsdx works perfectly fine if your text editor/ide supports typescript.

vongohren commented 4 years ago

Could we pin this issue like the who is using this lib issue? :)

ambroseus commented 4 years ago

How to configure project to use aliases in module's import to avoid '../../../' hell https://github.com/jaredpalmer/tsdx/pull/374#issuecomment-567687288 https://github.com/jaredpalmer/tsdx/issues/336

Screenshot from 2019-12-21 21-12-21

package.json

"devDependencies": {
  "babel-plugin-module-resolver": "^4.0.0"
}

tsconfig.json

"compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "comp": ["./src/comp"],
      "utils": ["./src/utils"],
      "*": ["src/*", "node_modules/*"]
    }
 }

.babelrc

  "plugins": [
    [
      "module-resolver",
      {
        "root": "./",
        "alias": {
          "comp": "./src/comp",
          "utils": "./src/utils",
          "*": ["src/*", "node_modules/*"]
        }
      }
    ]
  ]

advanced solution https://github.com/jaredpalmer/tsdx/pull/374#issuecomment-571667779 babel.config.js

module.exports = {
  // ...
  plugins: [
    // ... other plugins
    [
      'babel-plugin-module-resolver',
      {
        root: './',
        alias: require('./tsconfig.json').compilerOptions.paths,
      },
    ],
  ],
}
ambroseus commented 4 years ago

How to ship components with images properly https://github.com/jaredpalmer/tsdx/issues/278#issuecomment-563184800 https://github.com/jaredpalmer/tsdx/issues/386

thanks @vongohren for suggestion

tsdx.config.js

const images = require('@rollup/plugin-image');

module.exports = {
  rollup(config, options) {
    config.plugins = [
      images({ include: ['**/*.png', '**/*.jpg'] }),
      ...config.plugins,
    ]

    return config
  },
}
vongohren commented 4 years ago

For information, this might be fresh and good in the latest versions: https://github.com/jaredpalmer/tsdx/issues/379#issuecomment-601499240

Old history

@ambroseus why is your version so complex? What is the value going out of this? My suggestions results in a data string: const img = 'data:image/png;base64,iVBORw0KGgoAAAANSUh......

This is the code I ended up using

const images = require('@rollup/plugin-image');

module.exports = {
  rollup(config, options) {
    config.plugins = [
      images({ incude: ['**/*.png', '**/*.jpg'] }),
      ...config.plugins,
    ]

    return config
  },
}
vongohren commented 4 years ago

For information, this might be fresh and good in the latest versions: https://github.com/jaredpalmer/tsdx/issues/379#issuecomment-601499240

Old history

How to load a font into the code. This uses @rollup/plugin-url, and therefore I want @ambroseus suggestion to still be here. This long complex thing is needed because there is some async mechanism being used inside this library. Therefore we need to tackle that inside typescript with the following solution

Force inline wrapping the option in url plugin, tolimit:Infinity,. Force the plugin to emit files, use limit:0,

const url = require('@rollup/plugin-url')

module.exports = {
  rollup(config, options) {
    config.plugins = [
      // Force the `url` plugin to emit files.
      url({ include: ['**/*.ttf'] }),
      ...config.plugins,
    ]

    return config
  },
}

Then you can use this wherever you need in the code, also as a Global font face in emotion.

import React from 'react';
import { Global, css } from '@emotion/core'
import RalewayRegular from './assets/fonts/Raleway-Regular.ttf';

export default () => {
  return (
    <Global
      styles={css`
        @font-face {
          font-family: 'Raleway';
          font-style: normal;
          font-weight: 100 400;
          src: url(${RalewayRegular}) format('truetype');
        }
        body, button {
          font-family: 'Raleway', sans-serif;
        }
      `}
    />
  )
}
ambroseus commented 4 years ago

@vongohren thanks for the solution! @jaredpalmer @agilgur5 ^^^ +1 configuration hack :) , +1 to think about tsdx-plugins approach

arvigeus commented 4 years ago

A slightly better approach to configure aliases and avoid specifying folders manually:

package.json

"devDependencies": {
  "babel-plugin-module-resolver": "^4.0.0"
}

tsconfig.json (no paths)

"compilerOptions": {
  "include": [ "src" ],
  "baseUrl": "./src"
 }

babel.config.js

const { readdirSync } = require('fs');

const resolveAlias = readdirSync("./src", { withFileTypes: true })
    .filter(entry => entry.isDirectory())
    .reduce(
        (aliases, dir) => {
            aliases[dir.name] = "./src/" + dir.name;
            return aliases;
    }, { "*": ["src/*", "node_modules/*"] });

module.exports = function (api) {
  api.cache(true);

  return {
    plugins: [
      [ "module-resolver", { root: "./", alias: resolveAlias } ]
    ]
  };
}
arvigeus commented 4 years ago

There should be HOWTO for Visual Studio Code's Jest plugin as well (maybe something like eslint's "write to file")

arvinsim commented 4 years ago

@ambroseus @vongohren I tried using your @rollup/plugin-image solution.

Unfortunately, it is still not working. Both when importing it from an app and also by running storybook

I have tested it by using TSDX in my library while using CRA for my app. When I look into the src attribute of the imported img component, it is accessing /public/<minified name of image>.gif.

vongohren commented 4 years ago

@arvinsim that is strrange, because I use it in prod right now, and it works even fine in storybook The D is an image

Screenshot 2020-02-07 at 12 41 30

Are you using this comment? Because that is what im using

arvinsim commented 4 years ago

@vongohren May I know what version of TSDX and plugins that you are using? My package versions

"tsdx": "^0.12.3",
"@storybook/react": "^5.2.8",
"@rollup/plugin-image": "^2.0.0"

tsdx

arvinsim commented 4 years ago

@vongohren Okay so I found the issue. It was because babel-plugin-file-loader was set up. It overrode the output directory of @rollup/plugin-image. Once I remove it, it now works.

dclark27 commented 4 years ago

There should be HOWTO for Visual Studio Code's Jest plugin as well (maybe something like eslint's "write to file")

I was able to get the Jest plugin working by adding a jest.config.js file to my top level and adding:

module.exports = {
  transform: {
    '^.+\\.tsx?$': 'ts-jest'
  }
}
agilgur5 commented 4 years ago

Updating here as I did in #294 that async Rollup plugins are now supported out-of-the-box with v0.13.0, which was just released.

I've taken the liberty of editing some of the examples here to reflect that.

ambroseus commented 4 years ago

@agilgur5 awesome! HOWTO with rpt2 & objectHashIgnoreUnknownHack was removed

swyxio commented 4 years ago

How to configure a static assets folder

// tsdx.config.js
let static_files = require('rollup-plugin-static-files');

module.exports = {
  rollup(config) {
    config.plugins.push(
      static_files({
        include: ['./static'],
      })
    );
    return config;
  },
};

good for shipping static CSS that the user can import without assuming bundler setup

jaredpalmer commented 4 years ago

Let’s get these into the new docs site

brandoneggar commented 3 years ago

I'm posting this here in case it saves someone setup time with @rollup/plugin-image.

It needs to be added as the 1st plugin in your config.plugins array to work correctly!!!

const image = require('@rollup/plugin-image');

module.exports = {
  rollup(config, options) {
    config.plugins.push(
    //  ... your plugins here ...
    );

    // Per docs for @rollup/plugin-image it needs to be first plugin
    config.plugins.unshift(
      image({
        include: ['**/*.png', '**/*.jpg']
      })
    );

    return config;
  }
};
agilgur5 commented 3 years ago

@brandoneggar comments above already state that and put it first, so that is duplicative

shadiramadan commented 3 years ago

I tried to follow @vongohren's Font How-To https://github.com/formium/tsdx/issues/379#issuecomment-569011510

I added the rollup dependency:

yarn add --dev @rollup/plugin-url

Instead of .ttf files I use .woff2 in the tsdx.config.js example posted in the comment.

I had to add a fonts.d.ts file to the types folder for VSCode to not complain about my font imports:

declare module '*.woff2';

However, I'm having an issue in which the fonts are not being found when running yarn build

Error: Could not resolve './assets/fonts/MyFont/MyFont-Regular.woff2' from src/fonts.ts

    at error (/<user-path>/react-component-library/node_modules/rollup/dist/shared/node-entry.js:5400:30)

My fonts.ts file looks like:

import { css } from '@emotion/react'

import MyFontRegular from './assets/fonts/MyFont/MyFont-Regular.woff2';

export const fontStyles = css`
@font-face {
  font-family: 'My Font';
  font-style: normal;
  font-weight: 400;
  src: url(${MyFontRegular}) format('woff2');
}
`

I'm not sure where I am going wrong. This is basically off a vanilla tsdx project using the react-storybook template.

HerbCaudill commented 3 years ago

@ambroseus I struggled for some time with the .babelrc config for rewriting paths until I realized that module-resolver doesn't handle TypeScript files by default.

In your example, the options object should include an array of TypeScript extensions:

  "plugins": [
    [
      "module-resolver",
      {
        "root": "./",
        "alias": {
          "comp": "./src/comp",
          "utils": "./src/utils",
          "*": ["src/*", "node_modules/*"]
        },
        "extensions": [".ts", ".tsx"]
      }
    ]
  ]
Vadorequest commented 3 years ago

I've released https://github.com/UnlyEd/simple-logger and now I would like to automatically create a GitHub release when publishing to NPM, what github action do you recommend? Are there any example out there?

stephencweiss commented 3 years ago

@arvigeus , I think there's a small typo in your comment for aliasing for the tsconfig.json (link)

I believe this

"compilerOptions": {
  "include": [ "src" ],
  "baseUrl": "./src"
 }

should be this:

"include": [ "src" ],
"compilerOptions": {
  "baseUrl": "./src"
 }

(include is not a compilerOption in tsconfig)

drewgaze commented 3 years ago

@arvigeus

this solution doesn't appear to work for test execution, is there any workaround?

bk973 commented 2 years ago

I have an Issue. I want to know how to change port number when running an development mode.

saadjhk commented 2 years ago

How to configure a static assets folder

// tsdx.config.js
let static_files = require('rollup-plugin-static-files');

module.exports = {
  rollup(config) {
    config.plugins.push(
      static_files({
        include: ['./static'],
      })
    );
    return config;
  },
};

good for shipping static CSS that the user can import without assuming bundler setup

Hey, is it possible to include these static files within a specified directory, instead of just the root of dist

valenciaHQ commented 2 years ago

How to configure a static assets folder

// tsdx.config.js
let static_files = require('rollup-plugin-static-files');

module.exports = {
  rollup(config) {
    config.plugins.push(
      static_files({
        include: ['./static'],
      })
    );
    return config;
  },
};

good for shipping static CSS that the user can import without assuming bundler setup

Hey, is it possible to include these static files within a specified directory, instead of just the root of dist

up

valenciaHQ commented 2 years ago

I got HTML files within a node module that are being used as an email template. I got them under /template folder, but when I pack them, they are at /dist root, is there a way to save them under dist/template? Thanks!

ashishtwr314 commented 1 year ago

Import your assets like this , rather than using import: const asset = require('../**/*.png');

and in your tsdx.config.js

module.exports = {
  rollup(config, options) {
    config.plugins.push(
      images({ include: ['**/*.png', '**/*.jpg'] }),
      url({ exclude: ['**/*.png', '**/*.jpg'], limit: 0 }),
      ...otherconfig
    return config;
  },
};
hbisadii commented 1 year ago
      static_files({
        include: ['./static'],
      })

This works but when I set include: ['./src/assets', './src/styles'], it copies the files and folders in assets and styles straight into dist folder not under dists>assets and dist>styles

hbisadii commented 1 year ago
      static_files({
        include: ['./static'],
      })

This works but when I set include: ['./src/assets', './src/styles'], it copies the files and folders in assets and styles straight into dist folder not under dists>assets and dist>styles

The answer is I should have simply set include: ['./src'].