2
votes

I created a module using CRA (Create-React-App) - typescript and published the same to npm. My goal is to add the module as a component in another CRA created typescript project. When I try to import the module it fails with below error.

Cannot find module: 'fbdemots'. Make sure this package is installed. I do see the modules in the path "node_modules\fbdemots".

I tried the below which did not help

  1. Creating declaration files(d.ts) both in the module and the project which uses the module

  2. Updating the TSConfig as mentioned in below link

  3. Below links does not help, as I cannot change the "module": "esnext", --> to "CommonJS" since CRA (Create-React-App) does not allow me to. "moduleResolution": "node", "esModuleInterop" : "true"

`Cannot find module` for my own TypeScript module

1

1 Answers

0
votes

Wait! Why I see the fbdemots of node_modules is a project, not component, and it can't be exported at all

If you want to publish a component, you can follow these common steps, of course there are other methods you can try.

If you don't want to use rollup/webpack or feel a bit complicated, you can just export your plain component, and then publish it.

1. Create a component and export it

// index.tsx

import React from 'react'

const Test = (props: {a: string})=> <div>{props.a}</div>

export default Test

2. Using rollup or Webpack to build it to make sure it would be usable for JS modules

Install some necessary modules

yarn add --dev rollup rollup-plugin-typescript2

Then create rollup.config.js file at root, if there are other files like '.css', '.scss', then you should install and add some plugins like rollup-plugin-sass or rollup-plugin-css-only...

// rollup.config.js

import typescript from 'rollup-plugin-typescript2';
// import sass from 'rollup-plugin-sass';

export default {
  input: 'index.tsx', // the path of your source file
  output: [
    {
      dir: 'lib',
      format: 'cjs',
      exports: 'named',
      sourcemap: false,
      strict: false,
    },
  ],
  plugins: [typescript()],
  // plugins: [sass({ insert: true }), typescript()],
  external: ['react', 'react-dom'],
};

3. Create lib

Using the command of rollup to build it

npx rollup -c

And then prepare package.json, LICENSE, README.md... into lib dir, finally you can publish it

npm publish ./lib --access public

The end of the last, you can add it as a component in another CRA created typescript project!