GithubHelp home page GithubHelp logo

jaredpalmer / tsdx Goto Github PK

View Code? Open in Web Editor NEW
11.2K 46.0 508.0 3.71 MB

Zero-config CLI for TypeScript package development

Home Page: https://tsdx.io

License: MIT License

JavaScript 54.37% TypeScript 42.37% HTML 0.41% CSS 2.85%
typescript rollup npm yarn react packaging react-dom bundling jest

tsdx's Introduction

tsdx

Blazing Fast Blazing Fast Blazing Fast Discord

Despite all the recent hype, setting up a new TypeScript (x React) library can be tough. Between Rollup, Jest, tsconfig, Yarn resolutions, ESLint, and getting VSCode to play nicely....there is just a whole lot of stuff to do (and things to screw up). TSDX is a zero-config CLI that helps you develop, test, and publish modern TypeScript packages with ease--so you can focus on your awesome new library and not waste another afternoon on the configuration.

Features

TSDX comes with the "battery-pack included" and is part of a complete TypeScript breakfast:

  • Bundles your code with Rollup and outputs multiple module formats (CJS & ESM by default, and also UMD if you want) plus development and production builds
  • Comes with treeshaking, ready-to-rock lodash optimizations, and minification/compression
  • Live reload / watch-mode
  • Works with React
  • Human readable error messages (and in VSCode-friendly format)
  • Bundle size snapshots
  • Opt-in to extract invariant error codes
  • Jest test runner setup with sensible defaults via tsdx test
  • ESLint with Prettier setup with sensible defaults via tsdx lint
  • Zero-config, single dependency
  • Escape hatches for customization via .babelrc.js, jest.config.js, .eslintrc.js, and tsdx.config.js

Quick Start

npx tsdx create mylib
cd mylib
yarn start

That's it. You don't need to worry about setting up TypeScript or Rollup or Jest or other plumbing. Just start editing src/index.ts and go!

Below is a list of commands you will probably find useful:

npm start or yarn start

Runs the project in development/watch mode. Your project will be rebuilt upon changes. TSDX has a special logger for your convenience. Error messages are pretty printed and formatted for compatibility VS Code's Problems tab.

Your library will be rebuilt if you make edits.

npm run build or yarn build

Bundles the package to the dist folder. The package is optimized and bundled with Rollup into multiple formats (CommonJS, UMD, and ES Module).

npm test or yarn test

Runs your tests using Jest.

npm run lint or yarn lint

Runs Eslint with Prettier on .ts and .tsx files. If you want to customize eslint you can add an eslint block to your package.json, or you can run yarn lint --write-file and edit the generated .eslintrc.js file.

prepare script

Bundles and packages to the dist folder. Runs automatically when you run either npm publish or yarn publish. The prepare script will run the equivalent of npm run build or yarn build. It will also be run if your module is installed as a git dependency (ie: "mymodule": "github:myuser/mymodule#some-branch") so it can be depended on without checking the transpiled code into git.

Optimizations

Aside from just bundling your module into different formats, TSDX comes with some optimizations for your convenience. They yield objectively better code and smaller bundle sizes.

After TSDX compiles your code with TypeScript, it processes your code with 3 Babel plugins:

Development-only Expressions + Treeshaking

babel-plugin-annotate-pure-calls + babel-plugin-dev-expressions work together to fully eliminate dead code (aka treeshake) development checks from your production code. Let's look at an example to see how it works.

Imagine our source code is just this:

// ./src/index.ts
export const sum = (a: number, b: number) => {
  if (process.env.NODE_ENV !== 'production') {
    console.log('Helpful dev-only error message');
  }
  return a + b;
};

tsdx build will output an ES module file and 3 CommonJS files (dev, prod, and an entry file). If you want to specify a UMD build, you can do that as well. For brevity, let's examine the CommonJS output (comments added for emphasis):

// Entry File
// ./dist/index.js
'use strict';

// This determines which build to use based on the `NODE_ENV` of your end user.
if (process.env.NODE_ENV === 'production') {
  module.exports = require('./mylib.cjs.production.js');
} else {
  module.exports = require('./mylib.development.cjs');
}
// CommonJS Development Build
// ./dist/mylib.development.cjs
'use strict';

const sum = (a, b) => {
  {
    console.log('Helpful dev-only error message');
  }

  return a + b;
};

exports.sum = sum;
//# sourceMappingURL=mylib.development.cjs.map
// CommonJS Production Build
// ./dist/mylib.cjs.production.js
'use strict';
exports.sum = (s, t) => s + t;
//# sourceMappingURL=test-react-tsdx.cjs.production.js.map

AS you can see, TSDX stripped out the development check from the production code. This allows you to safely add development-only behavior (like more useful error messages) without any production bundle size impact.

For ESM build, it's up to end-user to build environment specific build with NODE_ENV replace (done by Webpack 4 automatically).

Rollup Treeshaking

TSDX's rollup config removes getters and setters on objects so that property access has no side effects. Don't do it.

Advanced babel-plugin-dev-expressions

TSDX will use babel-plugin-dev-expressions to make the following replacements before treeshaking.

__DEV__

Replaces

if (__DEV__) {
  console.log('foo');
}

with

if (process.env.NODE_ENV !== 'production') {
  console.log('foo');
}

IMPORTANT: To use __DEV__ in TypeScript, you need to add declare var __DEV__: boolean somewhere in your project's type path (e.g. ./types/index.d.ts).

// ./types/index.d.ts
declare var __DEV__: boolean;

Note: The dev-expression transform does not run when NODE_ENV is test. As such, if you use __DEV__, you will need to define it as a global constant in your test environment.

invariant

Replaces

invariant(condition, 'error message here');

with

if (!condition) {
  if ('production' !== process.env.NODE_ENV) {
    invariant(false, 'error message here');
  } else {
    invariant(false);
  }
}

Note: TSDX doesn't supply an invariant function for you, you need to import one yourself. We recommend https://github.com/alexreardon/tiny-invariant.

To extract and minify invariant error codes in production into a static codes.json file, specify the --extractErrors flag in command line. For more details see Error extraction docs.

warning

Replaces

warning(condition, 'dev warning here');

with

if ('production' !== process.env.NODE_ENV) {
  warning(condition, 'dev warning here');
}

Note: TSDX doesn't supply a warning function for you, you need to import one yourself. We recommend https://github.com/alexreardon/tiny-warning.

Using lodash

If you want to use a lodash function in your package, TSDX will help you do it the right way so that your library does not get fat shamed on Twitter. However, before you continue, seriously consider rolling whatever function you are about to use on your own. Anyways, here is how to do it right.

First, install lodash and lodash-es as dependencies

yarn add lodash lodash-es

Now install @types/lodash to your development dependencies.

yarn add @types/lodash --dev

Import your lodash method however you want, TSDX will optimize it like so.

// ./src/index.ts
import kebabCase from 'lodash/kebabCase';

export const KebabLogger = (msg: string) => {
  console.log(kebabCase(msg));
};

For brevity let's look at the ES module output.

import o from"lodash-es/kebabCase";const e=e=>{console.log(o(e))};export{e as KebabLogger};
//# sourceMappingURL=test-react-tsdx.esm.production.js.map

TSDX will rewrite your import kebabCase from 'lodash/kebabCase' to import o from 'lodash-es/kebabCase'. This allows your library to be treeshakable to end consumers while allowing to you to use @types/lodash for free.

Note: TSDX will also transform destructured imports. For example, import { kebabCase } from 'lodash' would have also been transformed to `import o from "lodash-es/kebabCase".

Error extraction

After running --extractErrors, you will have a ./errors/codes.json file with all your extracted invariant error codes. This process scans your production code and swaps out your invariant error message strings for a corresponding error code (just like React!). This extraction only works if your error checking/warning is done by a function called invariant.

Note: We don't provide this function for you, it is up to you how you want it to behave. For example, you can use either tiny-invariant or tiny-warning, but you must then import the module as a variable called invariant and it should have the same type signature.

⚠️Don't forget: you will need to host the decoder somewhere. Once you have a URL, look at ./errors/ErrorProd.js and replace the reactjs.org URL with yours.

Known issue: our transformErrorMessages babel plugin currently doesn't have sourcemap support, so you will see "Sourcemap is likely to be incorrect" warnings. We would love your help on this.

TODO: Simple guide to host error codes to be completed

Customization

Rollup

⚠️❗ 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!

TSDX uses Rollup under the hood. The defaults are solid for most packages (Formik uses the defaults!). However, if you do wish to alter the rollup configuration, you can do so by creating a file called tsdx.config.js at the root of your project like so:

// Not transpiled with TypeScript or Babel, so use plain Es6/Node.js!
module.exports = {
  // This function will run for each entry/format/env combination
  rollup(config, options) {
    return config; // always return a config.
  },
};

The options object contains the following:

export interface TsdxOptions {
  // path to file
  input: string;
  // Name of package
  name: string;
  // JS target
  target: 'node' | 'browser';
  // Module format
  format: 'cjs' | 'umd' | 'esm' | 'system';
  // Environment
  env: 'development' | 'production';
  // Path to tsconfig file
  tsconfig?: string;
  // Is error extraction running?
  extractErrors?: boolean;
  // Is minifying?
  minify?: boolean;
  // Is this the very first rollup config (and thus should one-off metadata be extracted)?
  writeMeta?: boolean;
  // Only transpile, do not type check (makes compilation faster)
  transpileOnly?: boolean;
}

Example: Adding Postcss

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

module.exports = {
  rollup(config, options) {
    config.plugins.push(
      postcss({
        plugins: [
          autoprefixer(),
          cssnano({
            preset: 'default',
          }),
        ],
        inject: false,
        // only write out CSS for the first bundle (avoids pointless extra files):
        extract: !!options.writeMeta,
      })
    );
    return config;
  },
};

Babel

You can add your own .babelrc to the root of your project and TSDX will merge it with its own Babel transforms (which are mostly for optimization), putting any new presets and plugins at the end of its list.

Jest

You can add your own jest.config.js to the root of your project and TSDX will shallow merge it with its own Jest config.

ESLint

You can add your own .eslintrc.js to the root of your project and TSDX will deep merge it with its own ESLint config.

patch-package

If you still need more customizations, we recommend using patch-package so you don't need to fork. Keep in mind that these types of changes may be quite fragile against version updates.

Inspiration

TSDX was originally ripped out of Formik's build tooling. TSDX has several similarities to @developit/microbundle, but that is because Formik's Rollup configuration and Microbundle's internals had converged around similar plugins.

Comparison with Microbundle

Some key differences include:

  • TSDX includes out-of-the-box test running via Jest
  • TSDX includes out-of-the-box linting and formatting via ESLint and Prettier
  • TSDX includes a bootstrap command with a few package templates
  • TSDX allows for some lightweight customization
  • TSDX is TypeScript focused, but also supports plain JavaScript
  • TSDX outputs distinct development and production builds (like React does) for CJS and UMD builds. This means you can include rich error messages and other dev-friendly goodies without sacrificing final bundle size.

API Reference

tsdx watch

Description
  Rebuilds on any change

Usage
  $ tsdx watch [options]

Options
  -i, --entry           Entry module
  --target              Specify your target environment  (default web)
  --name                Specify name exposed in UMD builds
  --format              Specify module format(s)  (default cjs,esm)
  --tsconfig            Specify your custom tsconfig path (default <root-folder>/tsconfig.json)
  --verbose             Keep outdated console output in watch mode instead of clearing the screen
  --onFirstSuccess      Run a command on the first successful build
  --onSuccess           Run a command on a successful build
  --onFailure           Run a command on a failed build
  --noClean             Don't clean the dist folder
  --transpileOnly       Skip type checking
  -h, --help            Displays this message

Examples
  $ tsdx watch --entry src/foo.tsx
  $ tsdx watch --target node
  $ tsdx watch --name Foo
  $ tsdx watch --format cjs,esm,umd
  $ tsdx watch --tsconfig ./tsconfig.foo.json
  $ tsdx watch --noClean
  $ tsdx watch --onFirstSuccess "echo The first successful build!"
  $ tsdx watch --onSuccess "echo Successful build!"
  $ tsdx watch --onFailure "echo The build failed!"
  $ tsdx watch --transpileOnly

tsdx build

Description
  Build your project once and exit

Usage
  $ tsdx build [options]

Options
  -i, --entry           Entry module
  --target              Specify your target environment  (default web)
  --name                Specify name exposed in UMD builds
  --format              Specify module format(s)  (default cjs,esm)
  --extractErrors       Opt-in to extracting invariant error codes
  --tsconfig            Specify your custom tsconfig path (default <root-folder>/tsconfig.json)
  --transpileOnly       Skip type checking
  -h, --help            Displays this message

Examples
  $ tsdx build --entry src/foo.tsx
  $ tsdx build --target node
  $ tsdx build --name Foo
  $ tsdx build --format cjs,esm,umd
  $ tsdx build --extractErrors
  $ tsdx build --tsconfig ./tsconfig.foo.json
  $ tsdx build --transpileOnly

tsdx test

This runs Jest, forwarding all CLI flags to it. See https://jestjs.io for options. For example, if you would like to run in watch mode, you can run tsdx test --watch. So you could set up your package.json scripts like:

{
  "scripts": {
    "test": "tsdx test",
    "test:watch": "tsdx test --watch",
    "test:coverage": "tsdx test --coverage"
  }
}

tsdx lint

Description
  Run eslint with Prettier

Usage
  $ tsdx lint [options]

Options
  --fix               Fixes fixable errors and warnings
  --ignore-pattern    Ignore a pattern
  --max-warnings      Exits with non-zero error code if number of warnings exceed this number  (default Infinity)
  --write-file        Write the config file locally
  --report-file       Write JSON report to file locally
  -h, --help          Displays this message

Examples
  $ tsdx lint src
  $ tsdx lint src --fix
  $ tsdx lint src test --ignore-pattern test/foo.ts
  $ tsdx lint src test --max-warnings 10
  $ tsdx lint src --write-file
  $ tsdx lint src --report-file report.json

Contributing

Please see the Contributing Guidelines.

Author

License

MIT

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Jared Palmer

📖 🎨 👀 🔧 ⚠️ 🚧 💻

swyx

🐛 💻 📖 🎨 🤔 🚇 🚧 👀

Jason Etcovitch

🐛 ⚠️

Sam Kvale

💻 ⚠️ 🐛 📖 👀 🤔 💬

Lucas Polito

💻 📖 💬

Steven Kalt

💻

Harry Hedger

🤔 📖 💻 💬

Arthur Denner

🐛 💻 💬

Carl

🤔 📖 💻 ⚠️ 💬

Loïc Mahieu

💻 ⚠️

Sebastian Sebald

📖 💻 ⚠️

Karl Horky

📖 🤔

James George

📖

Anton Gilgur

🚧 📖 💻 🐛 💡 🤔 💬 👀 ⚠️

Kyle Holmberg

💻 💡 ⚠️ 👀 💬

Sigurd Spieckermann

🐛 💻

Kristofer Giltvedt Selbekk

💻

Tomáš Ehrlich

🐛 💻

Kyle Johnson

🐛 💻

Etienne Dldc

🐛 💻 ⚠️

Florian Knop

🐛

Gonzalo D'Elia

💻

Alec Larson

💻 👀 🤔 💬

Justin Grant

🐛 🤔 💬

Jirat Ki.

💻 ⚠️ 🐛

Nate Moore

💻 🤔

Haz

📖

Basti Buck

💻 🐛

Pablo Saez

💻 🐛

Jake Gavin

🐛 💻

Grant Forrest

💻 ⚠️ 🐛

Sébastien Lorber

💻

Kirils Ladovs

📖

Enes Tüfekçi

💻 📖

Bogdan Chadkin

👀 💬 🤔

Daniel K.

💻 📖 ⚠️ 🤔 🐛

Quentin Sommer

📖

Hyan Mandian

💻 ⚠️

Sung M. Kim

🐛 💻

John Johnson

💻 📖

Jun Tomioka

💻 ⚠️

Leonardo Dino

💻 🐛

Honza Břečka

💻 🐛

Ward Loos

💻 🤔

Brian Bugh

💻 🐛

Cody Carse

📖

Josh Biddick

💻

Jose Albizures

💻 ⚠️ 🐛

Rahel Lüthy

📖

Michael Edelman

💻 🤔

Charlike Mike Reagent

👀 💻 🤔

Frederik Wessberg

💬

Elad Ossadon

💻 ⚠️ 🐛

Kevin Kipp

💻

Matija Folnovic

💻 📖

Andrew

💻

Ryan Castner

💻 ⚠️ 🤔

Yordis Prieto

💻

NCPhillips

📖

Arnaud Barré

💻 📖

Peter W

📖

Joe Flateau

💻 📖

H.John Choi

📖

Jon Stevens

📖 🤔 🐛

greenkeeper[bot]

🚇 💻

allcontributors[bot]

🚇 📖

dependabot[bot]

🚇 🛡️ 💻

GitHub

🚇

Eugene Samonenko

⚠️ 💡 💬 🤔

Joseph Wang

🐛

Kotaro Sugawara

🐛 💻

Semesse

💻

Bojan Mihelac

💻

Dan Dascalescu

📖

Yuriy Burychka

💻

Jesse Hoyos

💻

Mike Deverell

💻

Nick Hehr

💻 📖 💡

Bnaya Peretz

🐛 💻

Andres Alvarez

💻 📖 💡

Yaroslav K.

📖

Dragoș Străinu

🤔

George Varghese M.

💻 📖 ⚠️

Reinis Ivanovs

🤔 💬

Orta Therox

💬 📖

Martijn Saly

🐛

Alex Johansson

📖

hb-seb

💻

seungdols

🐛

Béré Cyriac

🐛

Dmitriy Serdtsev

🐛

Vladislav Moiseev

💻

Felix Mosheev

🐛 📖

Ludovico Fischer

💻

Altrim Beqiri

🐛 💻 ⚠️

Tane Morgan

🐛 💻

This project follows the all-contributors specification. Contributions of any kind welcome!

tsdx's People

Contributors

agilgur5 avatar aleclarson avatar allcontributors[bot] avatar arthurdenner avatar audiolion avatar dependabot[bot] avatar fredyc avatar goznauk avatar greenkeeper[bot] avatar hedgerh avatar jakegavin avatar jamesgeorge007 avatar jaredpalmer avatar kylemh avatar leonardodino avatar lookfirst avatar mfolnovic avatar n3tr avatar natemoo-re avatar netzwerg avatar nstfkc avatar pabloszx avatar pete-redmond-cko avatar quentin-sommer avatar sadsa avatar sam-kvale-sap avatar samdenty avatar swyxio avatar techieshark avatar yordis avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tsdx's Issues

Can't use hooks when `react` & `react-dom` are dev dependencies

Current Behavior

Thank you for this project!

I'm not sure if I missed or didn't understand something, but when choosing the react template, react & react-dom are added as dev dependencies. When you then try to use a hook inside your library, you get a react-invalid-hook-call error. It works fine when removing them as dev dependencies and running yarn again.

Example:

export const Thing = () => {
  const [fooBar, setFooBar] = React.useState('foo');

  return (
    <div onClick={() => setFooBar('bar')}>
      the snozzberries taste like {fooBar}
    </div>
  );
};

Expected behavior

I would expect the template to enable me to use hooks.

Suggested solution(s)

No idea if "just removing the dev dependencies" is the proper solution. It at least worked for me.

Your environment

Software Version(s)
TSDX 0.5.4
TypeScript 3.4.5
Browser Chrome 74.0.3729.108
npm/Yarn Yarn 1.12.3
Operating System MacOS 10.14.4

Relative imports are treated as external on Windows

Current Behavior

My code isn't getting bundled because tsdx treats everything as external modules, the resulting bundle only contains the compiled index.ts file.

Expected behavior

My files shouldn't be treated as external modules.

Suggested solution(s)

Could it be something related to the external function? https://github.com/palmerhq/tsdx/blob/v0.5.7/src/utils.ts#L19

Additional context

I'm getting the following warning for all my .ts files (except the root index.ts file):

No name was provided for external module 'C:/xyz/xyz/xyz/xyz.ts' in output.globals – guessing 'xyz_ts'

Your environment

Software Version(s)
TSDX 0.5.7
TypeScript 3.4.5
Browser Chrome Version 74.0.3729.131
npm/Yarn Node v10.11.0, npm 6.4.1
Operating System Windows 10

vscode doesn't use tsconfig.json settings for files in test folder

Current Behavior

When I set experimentalDecorators to true in tsconfig.json it works ok for files in "src", but it doesn't work for files in "test" (vscode marks decorators in red, but it works ok when running 'test')

Desired Behavior

When experimentalDecorators is set to true in tsconfig.json it should also be for vscode test files

Suggested Solution

Add a tsconfig.json file to the tests folder:

{
 "extends": "../tsconfig.json",
 "include": ["."]
}

with any other overrides that might be needed to make tests work and make jest use that one.

Who does this impact? Who is this for?

Libs that use experimental decorators

Describe alternatives you've considered

N/A

Additional context

N/A

No tests found - exit code 1

Current Behavior

After installing tsdx globally and creating a new project I ran npm test and it prompts the following to console:

No tests found, exiting with code 1
Run with `--passWithNoTests` to exit with code 0
In C:\dev\hidash
  13 files checked.
  testMatch: C:/dev/hidash/test/**\?(*.)(spec|test).{ts,tsx} - 0 matches
  testPathIgnorePatterns: \\node_modules\\ - 13 matches
  testRegex:  - 0 matches
Pattern:  - 0 matches

Also when filtering for blah.test.ts manually it won't show up.

Expected behavior

To get the default test to run and pass after installing out of the box.

Your environment

Software Version(s)
TSDX 0.5.4
TypeScript as bundled
Browser (not involved)
npm 6.7.0
Operating System Windows 10

`tsdx build` converts from kebab case to camel case

Current Behavior

if i have a package named "react-netlify-identity-widget" and i run tsdx build on it, the package.json has these fields:

  "umd:main": "dist/react-netlify-identity-widget.umd.production.js",
  "module": "dist/react-netlify-identity-widget.es.production.js",

however the filenames are camelcase: reactNetlifyIdentityWidget.cjs.production.js

Expected behavior

files should match up.

Suggested solution(s)

i'm actually not sure where the camelcasing pops up. took a quick look thru the code and couldnt find it.

maybe the super simple solution is to also camelcase the package.json naming. but probably the right solution is to preserve kebab case everywhere

README instructions don't work

Current Behavior

I'm following the README instructions, and it seems like they're geared towards tsdx being an NPM script in an existing project?

$ cd ~/dev
$ yarn tsdx create my-lib
yarn run v1.13.0
error Couldn't find a package.json file in "/Users/jasonetco/dev"
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

I also tried yarn global add tsdx and then running tsdx create my-lib:

Error: /Users/jasonetco/dev/package.json: ENOENT: no such file or directory, open '/Users/jasonetco/dev/package.json'

This even happens when I run tsdx --version.

Expected behavior

I could be misunderstanding the tool, but I'm guessing this should scaffold out the folder? Not sure why it's trying to read an existing package.json.

Your environment

Software Version(s)
npm/Yarn npm: 6.4.1 yarn: 1.13.0
Operating System MacOS Mojave

`yarn jest` TypeError: xxx.default is not a constructor -- default export not output as expected

Current Behavior

tsdx yarn test will report error:

TypeError: xxx.default is not a constructor

when import a class created by tsdx and try to instance it.

reproduction:

  1. create a lib using tsdx
tsdx create mylib-a
  1. modify index.ts to a class
// mylib-a/src/index.ts
export default class MyLibA {}
  1. build
yarn build
  1. create another lib using tsdx called mylib-b
  2. move mylib-a to mylib-b/src/
  3. import mylib-a in mylib-b/test/blah.test.ts
import MyLibA from '../src/mylib-a';
// this line is error when `yarn test`
// TypeError: xxx.default is not a constructor
const instance = new MyLibA();
  1. yarn test

If I don't use default to export class:

export class MyLibA {}

And import like this:

import { MyLibA } from ...;

Everything will be ok, but it is just a workaround.

Expected behavior

Suggested solution(s)

Additional context

Your environment

Software Version(s)
TSDX ^0.5.6
TypeScript ^3.4.5
Browser -
npm/Yarn [email protected]
Operating System macOS Mojave version 10.14.4 (18E226)

`npx tsdx create` fails when Yarn is not installed

Current Behavior

Running tsdx create without having Yarn installed results in an error like this:

% npx tsdx create edzif-zz
✔ Created edzif-zz
✖ Failed to install dependencies
Error: spawn yarn ENOENT

    at Process.ChildProcess._handle.onexit (internal/child_process.js:240:19)
    at onErrorNT (internal/child_process.js:415:16)
    at process._tickCallback (internal/process/next_tick.js:63:19)

% yarn
zsh: command not found: yarn

Expected behavior

tsdx's documentation could be read like it works with "plain npm", and thus I had expected it to work just having node

Suggested solution(s)

  1. If Yarn is required, it should probably be made clear.
  2. If not, tsdx create should work without Yarn.

Additional context

N/A

Your environment

Software Version(s)
TSDX latest (using npx)
TypeScript N/A
Browser N/A
npm/Yarn 6.9.0
Operating System macOS "Mojave" 14.4.0

General notes

👋 In trying out this tool, I wanted to leave some general notes for you. Feel free to close this issue right away, or use it to spawn further issues - totally up to you.


Tiny thing in the generated package.json:

image


Would be cool to supe up the bootstrap logs:

image

Adding some emojis, maybe some color?

➡️ Bootstrapping new project...
📦 Installing dependencies...

✅ Success! TSDX just bootstrapped a brand new project for you. To get started, run:

      cd my-lib
      yarn start

Potentially add a linter - its a hot topic, and I'm not sure how opinionated you want this tool to be. Maybe a section in the README? I mention it because to me, "out of the box" includes a linter - but it may not to other people so 🤷‍♂️


Generated README is a little bare which is totally fine, but it could be nice to add something like this: https://github.com/jasonetco/stub-template#readme


Now, off to try using it with a real project...

`create` script fails and is looking for a `package.json` again

Current Behavior

~/dev/tsdx-test
$ npx tsdx create mylib
/Users/jasonetco/dev/tsdx-test/package.json: ENOENT: no such file or directory, open '/Users/jasonetco/dev/tsdx-test/package.json'

~/dev/tsdx-test
$ npm i -g tsdx
...
+ [email protected]
added 940 packages from 512 contributors in 24.628s

~/dev/tsdx-test took 25s 254ms
$ tsdx create mylib
✖ Failed to create mylib
Error: ENOENT: no such file or directory, stat '/Users/jasonetco/.nvm/versions/node/v10.13.0/lib/node_modules/tsdx/template'

Possibly relates to #2

Your environment

Software Version(s)
TSDX v0.0.25

install tslib by default

Libraries should be using tslib to eliminate duplicate code.

Also need "importHelpers": true in the tsconfig.json

react library with scss modules support

Current Behavior

Is not possible to use it with scss and module

Desired Behavior

Be able to use it as CRA

scss file: helloWorld.module.scss

ts: import style from "./helloWorld.module.scss"

Suggested Solution

Have a look on CRA and see how it works

Who does this impact? Who is this for?

All the developer that want to create a library with multiple modules and have support of scss

code splitting support

Current Behavior

currently we bundle single files, named per environment/module format.

to support code splitting (which is the default behavior of Rollup v1 which we just upgraded to) we'll have to evolve this to a folder format with multiple files.

right now this https://github.com/sw-yx/react-netlify-identity-widget/blob/master/src/index.tsx#L8 doesnt produce a separate bundle for me :(

Desired Behavior

code splitting support.

Suggested Solution

as above

Who does this impact? Who is this for?

all users, partiuclarly React users, who want to offer code splitting as a feature

Describe alternatives you've considered

no change

Additional context

i'm unsure what existing priorities this may conflict with for you.

`dist` not included in default publish experience

Current Behavior

Currently the scaffolded package.json looks like this:

{
  "source": "src/index.ts",
  "main": "index.js",
  "umd:main": "dist/podcats.umd.production.js",
  "module": "dist/podcats.es.production.js",
  "typings": "dist/index.d.ts",
  "scripts": {
    "start": "tsdx watch",
    "build": "tsdx build",
    "test": "tsdx test"
  },
  "devDependencies": {
// etc
  }
}

when i publish to npm, nothing in the dist folder gets included. this could partially be because of the .gitignore (in which case we should add an .npmignore?) but i think the "main": "index.js", line is also a problem. I'm quite inexperienced at this so i'm not sure how to fix but i'm sure you can.

Expected behavior

i can just type 'yarn publish' at the root level and it "just works"

Suggested solution(s)

fix "main" field?

Your environment

Software Version(s)
TSDX 0.2.5
TypeScript 3.2.4
Browser chrome
  System:
    OS: macOS High Sierra 10.13.4
    CPU: (4) x64 Intel(R) Core(TM) i7-7660U CPU @ 2.50GHz
    Memory: 127.70 MB / 16.00 GB
    Shell: 5.3 - /bin/zsh
  Binaries:
    Node: 11.0.0 - /usr/local/bin/node
    Yarn: 1.12.1 - /usr/local/bin/yarn
    npm: 6.4.1 - /usr/local/bin/npm
  Browsers:
    Chrome: 71.0.3578.98
    Safari: 11.1

Creation failure - TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type object

Current Behavior

When running npx tsdx create mylib, the installation fails with the error:

√ Created mylib
× Failed to install dependencies
TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type object

    at assertPath (path.js:39:11)
    at Object.normalize (path.js:285:5)
    at parseNonShell (C:\Users\kevin\AppData\Roaming\npm-cache\_npx\12552\node_modules\tsdx\node_modules\execa\node_modules\cross-spawn\lib\parse.js:54:31)
    at Function.parse [as _parse] (C:\Users\kevin\AppData\Roaming\npm-cache\_npx\12552\node_modules\tsdx\node_modules\execa\node_modules\cross-spawn\lib\parse.js:122:49)
    at handleArgs (C:\Users\kevin\AppData\Roaming\npm-cache\_npx\12552\node_modules\tsdx\node_modules\execa\index.js:41:23)
    at Object.module.exports [as default] (C:\Users\kevin\AppData\Roaming\npm-cache\_npx\12552\node_modules\tsdx\node_modules\execa\index.js:199:17)
    at prog.version.command.describe.action (C:\Users\kevin\AppData\Roaming\npm-cache\_npx\12552\node_modules\tsdx\dist\index.js:172:30)

Expected behavior

Should successfully generate the full template, install deps, etc.

Additional context

I tried poking around in the code and can see that it's failing on

await execa(getInstallArgs(getInstallCmd(), deps));

As far as I can tell, it's trying to run via yarn on my machine.

Your environment

Software Version(s)
TSDX 0.5.0
TypeScript
Browser
npm/Yarn 6.4.1/1.13.0
Operating System Windows 10 Pro (1809)

TypeError: Cannot read property 'find' of undefined

I have an existing project that uses microbundle and I wanted to give this project a shot.

Current Behavior

When I run tsdx build I get this error, but the outputted dist folder seems fine.

❯ npx tsdx build
✓ Creating entry file 2.1 secs
(node:7935) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'find' of undefined
    at then.then (/home/z0al/x/github/stash/packages/core/node_modules/rollup-plugin-size-snapshot/dist/treeshakeWithRollup.js:67:36)
(node:7935) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:7935) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Expected behavior

No errors

Suggested solution(s)

Additional context

Your environment

Software Version(s)
TSDX 0.5.4
TypeScript 3.4.5
Browser N/A
npm/Yarn npm
Operating System Debian/Linux

Unclear error for missing "source"

Current Behavior

Tried dropping TSDX into an existing library, and got this:

> [email protected] build /Users/jasonetco/dev/actions-toolkit
> tsdx build

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined

    at assertPath (path.js:39:11)
    at Object.resolve (path.js:1088:7)
    at Object.exports.resolveApp (/Users/jasonetco/dev/actions-toolkit/node_modules/tsdx/dist/utils.js:19:27)
    at Object.createRollupConfig (/Users/jasonetco/dev/actions-toolkit/node_modules/tsdx/dist/createRollupConfig.js:29:24)
    at createBuildConfigs (/Users/jasonetco/dev/actions-toolkit/node_modules/tsdx/dist/index.js:30:30)
    at prog.command.describe.action (/Users/jasonetco/dev/actions-toolkit/node_modules/tsdx/dist/index.js:130:37)
    at Sade.parse (/Users/jasonetco/dev/actions-toolkit/node_modules/sade/lib/index.js:153:56)
    at Object.<anonymous> (/Users/jasonetco/dev/actions-toolkit/node_modules/tsdx/dist/index.js:168:6)
    at Module._compile (internal/modules/cjs/loader.js:688:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:699:10)

After some 🤔, turns out it was expecting a "source" property in my package.json.

Expected behavior

A handy-dandy error like:

Hey you need a `source` property in your package.json, pointing to the entrypoint of your library

Your environment

Software Version(s)
TSDX v0.0.25

Standardize commit and release

Current Behavior

No standardized commit messages or release process for created libraries.

Desired Behavior

yarn commit with prompts and linting + yarn release

Suggested Solution

Something like conventional commits + git-cz + semantic release.

Add prettier

eslint and prettier are the basic tools for any repo these days. You've got the issue for eslint, so I've thought I'd open up one for prettier too.

Out-of-the-box `npm test` fails

Current Behavior

$ npx tsdx create tsdx-test
$ cd tsdx-test && npm test

> [email protected] test /Users/jasonetco/dev/tsdx-test
> tsdx test

● Validation Error:

  Module /Users/jasonetco/dev/tsdx-test/node_modules/tsdx/node_modules/ts-jest in the transform option was not found.
         <rootDir> is: /Users/jasonetco/dev/tsdx-test

  Configuration Documentation:
  https://jestjs.io/docs/configuration.html

npm ERR! Test failed.  See above for more details.

[0.3.0] dist/index.js is still a nonexistent file

Current Behavior

despite the recent improvements, tsdx still scaffolds to something like this:

{
  "name": "podcats",
  "version": "0.1.5",
  "main": "dist/index.js",
  "umd:main": "dist/podcats.umd.production.js",
  "module": "dist/podcats.es.production.js",
  "typings": "dist/index.d.ts",
  "files": [
    "dist"
  ],
  "scripts": {
    "start": "tsdx watch",
    "build": "tsdx build",
    "test": "tsdx test"
  },
  "devDependencies": {
    "@types/jest": "^23.3.13",
    "tsdx": "^0.3.0",
    "typescript": "^3.2.4",
  }
}

in particular, i believe that "main": "dist/index.js", is invalid.

as a result, the library builds, but when it is required into other apps, node resolution fails to find the library.

Expected behavior

i may be wrong but i think it should point to "main": "dist/index.js",

CLI version is missing

Current Behavior

npx tsdx -v returns tsdx, 0.0.0

Expected behavior

proper version

Your environment

Software Version(s)
TSDX 0.3.0
TypeScript 3.x
Browser chrome

    OS: macOS High Sierra 10.13.4
    Node: 10.13.0 - ~/.nvm/versions/node/v10.13.0/bin/node
    Yarn: 1.12.1 - /usr/local/bin/yarn
    npm: 6.4.1 - ~/.nvm/versions/node/v10.13.0/bin/npm

compress option in `terser` inside production es rollup config produces invalid JS

Current Behavior

here is my repo i'm working on https://github.com/sw-yx/react-netlify-identity-widget/tree/rollupProductionIssue

if you:

yarn build
yarn link
cd example
yarn && yarn link "react-netlify-identity"
yarn start

you will see this error:

image

however if you change the package.json to use the development versions:

image

it works!!

to me this indicates a rollup config issue.

Expected behavior

the production output should work the same as development output

Suggested solution(s)

i think this could be a terser bug. or a setting that is incompatible with React.

here is the offending unexpected token - prettified for easier reading

image

i'm not sure what rollup setting caused this but it definitely only exists in the production build.

Your environment

Software Version(s)
TSDX 0.3.4
TypeScript 3.4.4
Browser chrome
npm/Yarn yarn
Operating System osx

upgrade to Rollup 1.0

Current Behavior

rollup 1.0 was released in december: rollup/rollup#2293

including dynamic imports, which i want

any considerations that have held you back that we should think about?

Skipping a format results in warning about an unhandled promise rejection

Current Behavior

Skipping one of the module formats causes a warning about an unhandled promise rejection due to an invalid rollup config.

> tsdx build --format cjs,es

(node:94549) UnhandledPromiseRejectionWarning: Error: You must supply an options object to rollup
    at getInputOptions$1 (/Users/jake/Desktop/mylib/node_modules/rollup/dist/rollup.js:18675:15)
    at Object.rollup (/Users/jake/Desktop/mylib/node_modules/rollup/dist/rollup.js:18732:30)
    at asyncro_1.default.map (/Users/jake/Desktop/mylib/node_modules/tsdx/dist/index.js:293:41)
    at Array.map (<anonymous>)
    at Object.n [as map] (/Users/jake/Desktop/mylib/node_modules/asyncro/dist/asyncro.js:1:100)
    at prog.command.describe.option.example.option.example.option.example.option.example.action (/Users/jake/Desktop/mylib/node_modules/tsdx/dist/index.js:292:43)
(node:94549) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 3)
(node:94549) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
✓ Creating entry file 3.5 secs

As far as I can tell, the build still succeeds though so this isn't a huge issue.

Expected behavior

Ideally, the build would run without any warnings.

Suggested solution(s)

One possible solution would be to filter falsey values from the createBuildConfigs call: #77

Additional context

Thanks for the work you put into this!

Your environment

Software Version(s)
TSDX 0.5.5
TypeScript 3.4.5
Browser Chrome
npm/Yarn npm 6.4.1
Operating System MacOS 10.13.6

Better Logging

The rollup output is wayyyyyy too verbose. Need to make it concise.

Consider splitting out the create command

Current Behavior

tsdx create is just another cli command. However, it shares almost zero code with the other commands and in fact makes things harder for them since certain values like paths.js are all undefined.

Desired Behavior

Split out the creation script into a separate package or isolate the code so that it does not interfere or cause headaches throughout the rest of the codebase

Suggested Solution

  • Make a separate create-ts-project package. Thanks to the create prefix, it will work with yarn create. So people will be able to enter yarn create ts-project (instead of using npx).
  • Gluegun appears to have support for templating use .ejs, so that's worth evaluating during #17

Who does this impact? Who is this for?

Errbody.

Multiple entries

This was technically added in 0.3.0, but needs documentation. Additionally, we need to think through dev/prod builds for each output and if that is what people actually want or nah.

[Feature] .env support like CRA and @vue/cli

Current Behavior

process.env.* transpiles as is

Desired Behavior

declared variable with prefix TLDX_* transpiles to its values. Other vars transpiles as is

if .env contents:

TLDX_KEY=key
KEY=blah-blah

then process.env.TLDX_KEY transpiles to key and process.env.KEY transpiles to process.env.KEY

Who does this impact? Who is this for?

This is for my team. We building the package with opt-in features and some client-specific keys. Also, CRA and @vue/cli have this feature too.

Error: ENOENT: no such file or directory -- templates dir is missing

Current Behavior

When I run tsdx create mylib I receive the following error:

Error: ENOENT: no such file or directory, stat '/usr/local/lib/node_modules/tsdx/templates/basic'

Expected behavior

I'm not sure,I haven't gotten it to work yet 😄

Suggested solution(s)

N/A

Additional context

I have seen other similar errors reported and they were marked as closed. Not sure why I'm having this issue.

Your environment

Software Version(s)
TSDX 0.5.3
TypeScript 3.4.5
Browser Google Chrome
npm/Yarn 6.9.0
Operating System 10.14.4

Creation failure - The "file" argument must be of type string

Current Behavior

When running npx tsdx create myapp, the installation fails with the error:

✔ Created myapp
✖ Failed to install dependencies
TypeError [ERR_INVALID_ARG_TYPE]: The "file" argument must be of type string. Received type object

    at validateString (internal/validators.js:125:11)
    at normalizeSpawnArguments (child_process.js:399:3)
    at Object.spawn (child_process.js:532:38)
    at Object.module.exports [as default] (/Users/james.quigley/.npm/_npx/49155/lib/node_modules/tsdx/node_modules/execa/index.js:205:26)
    at prog.version.command.describe.action (/Users/james.quigley/.npm/_npx/49155/lib/node_modules/tsdx/dist/index.js:172:30)

Expected behavior

Should successfully generate the full template, install deps, etc.

Suggested solution(s)

Seems like a type error. Can investigate more later unless someone beats me to it

Additional context

Your environment

Software Version(s)
TSDX 0.5.0
TypeScript
Browser
npm/Yarn 6.9/1.15.2
Operating System MacOS Mojave

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.