The process of compiling and monitoring *two* Typescript packages, where one is reliant on the other

I'm in the process of creating a Typescript library located under src/ and sample files under examples/. The current directory structure is as follows:

examples/
    package.json
    exampleFiles.ts
src/
    index.ts
package.json

I am able to compile the library following these guidelines, but I am unsure about how to simultaneously monitor both projects, particularly when one relies on the other.

This is what examples/package.json contains:

{
  "dependencies": {
    "my-project": "file:..",
  }
}

In essence, I have implemented a file: dependency to avoid constant publishing of the library to npm and reinstalling it. Hopefully, this method will prove beneficial.

Any suggestions on streamlining this setup for seamless development?

Answer №1

To extract DTS files from the source package and then provide them to the examples package, consider creating a tsconfig.json file in both packages.

Answer №2

Understanding this may be a bit challenging, but it seems to be functioning as intended:

package.json

{
  "name": "my-lib",
  "version": "0.3.0",
  "types": "src/index.ts", <-- crucial
  ...
}

examples/package.json

{
  "dependencies": {
    "react": "^15.6.1",
    "react-redux": "^5.0.5",
    "redux": "^3.7.2"
  },
  "devDependencies": {
    "@types/react": "^16.0.0",
    "@types/react-dom": "^15.5.1",
    "awesome-typescript-loader": "^3.2.2",
    "url-loader": "^0.5.9",
    "webpack": "^3.4.1",
    "webpack-dev-server": "^2.6.1"
  }
}

examples/webpack.config.babel.js

import {ProvidePlugin} from 'webpack';
import {CheckerPlugin, TsConfigPathsPlugin} from 'awesome-typescript-loader';

export default {
    context: `${__dirname}/src`,
    entry: './index.tsx',
    output: {
        path: `${__dirname}/src`,
        filename: 'bundle.js',
        publicPath: '/',
        pathinfo: true,
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/, 
                loader: 'awesome-typescript-loader'
            },
            {
                test: /\.(jpe?g|png|gif)($|\?)/i,
                // include: __dirname,
                loader: 'url-loader',
                options: {
                    limit: 1024 * 2,
                }
            },
        ]
    },
    target: 'web',
    resolve: {
        modules: ['node_modules'],
        extensions: ['.tsx', '.ts', '.jsx', '.js'],
        plugins: [
            new TsConfigPathsPlugin()
        ],
    },
    devtool: 'cheap-module-eval-source-map',
    plugins: [
        new ProvidePlugin({
            React: 'react',
        }),
        new CheckerPlugin(),
    ]
};

examples/.babelrc

This allows the use of import in the webpack.config.babel.js.

{
  "presets": [
    [
      "env",
      {
        "targets": {
          "node": "current"
        }
      }
    ]
  ]
}

examples/tsconfig.json

{
  "compilerOptions": {
    "strict": true,
    "importHelpers": false,
    "removeComments": false,
    "preserveConstEnums": false,
    "sourceMap": true,
    "inlineSources": true,
    "noEmitOnError": false,
    "pretty": true,
    "outDir": "dist",
    "target": "es2017",
    "downlevelIteration": false,
    "lib": [
      "esnext",
      "dom"
    ],
    "moduleResolution": "node",
    "declaration": true,
    "module": "ESNext",
    "types": [
      "node"
    ],
    "baseUrl": ".", <-- necessary
    "paths": {
      "my-lib": [
        ".."  <-- enables importing 'my-lib' without npm publishing
      ]
    },
    "jsx": "React",
    "allowSyntheticDefaultImports": true
  },
  "files": [
    "src/index.tsx"
  ]
}

examples/Makefile

I prefer using Make over npm scripts.

# these are not files
.PHONY: all clean

# disable default suffixes
.SUFFIXES:

all: yarn.lock
    npx webpack-dev-server --hot --inline --colors --port 3123 --content-base src

yarn.lock:: package.json
    @yarn install --production=false
    @touch -mr $@ $<

yarn.lock:: node_modules
    @yarn install --production=false --check-files
    @touch -mr $@ $<

node_modules .deps:
    mkdir -p $@

clean:
    rm -rf node_modules dist

Running

To execute this setup smoothly, navigate to the examples directory and run the command make. This will launch webpack-dev-server, monitor your files, and reload automatically.

Implementing hot loading for React components requires additional steps.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Faulty deduction can occur when implementing the return statement in an identity function, or when incorporating an optional parameter

Encountering strange behavior while working on identity functions in a wizard system schema. Using a constrained identity function for inference is causing issues with one property that cannot be inferred when using the following: When the return value fr ...

Issue with VS2017RC: TypeScript fails to produce JavaScript files

After updating to VS 2017, I noticed that modifications made to a typescript file no longer result in the generation of any javascript code, despite receiving a message indicating "outputs generated successfully" on the lower bar. I tested this issue on t ...

The 'Element[]' type is lacking certain properties when dealing with react children

In my code, there is a parent component passing down its children to a child component. These children can be either single nodes or arrays of nodes, and the ChildComponent renders them differently based on their type. However, when I try to render the Chi ...

Troubleshooting issues with bash version 4.3.2 (npm installations failing to work)

After recently downloading bash version 4.3.2, I was excited to experiment with it. However, I encountered an issue when trying to run npm install for typescript and gulp, as the commands were not found. -bash: typescript: command not found -bash: gulp: c ...

Exploring the Method of Utilizing JSON Attribute in typeScript

How to access JSON attributes in TypeScript while working on an Angular Project? I'm currently in the process of building an Angular project and I need to know how to access JSON attributes within TypeScript. test:string; response:any; w ...

Npm is refusing to install quick.db and is displaying these error messages

I'm currently facing an issue while trying to set up quick.db for my discord.js bot. I followed the installation process by running the following two commands: npm -g --add-python-to-path install windows-build-tools node-gyp and npm i quick.db Howev ...

Attempting to access a specific JSON key using Observables

Apologies for the question, but I'm relatively new to Typescript and Ionic, and I find myself a bit lost on how to proceed. I have a JSON file containing 150 entries that follow a quite simple interface declaration: export interface ReverseWords { id ...

When trying to execute the maven-exec-plugin with the npm run build command, an error occurred stating that the build command can only be run within

I have developed a Maven application that compiles an Angular application within a Docker container. In the pom.xml file, I included the following configuration: [...] <execution> <id>npm run build</id> ...

Mastering the art of Interpolation and Binding in Ionic 3/Angular 4: A step-by-step

My goal is to retrieve data from my Parse Server where MongoDB is installed. Although I have successfully displayed the data in the console, I am facing issues interpolating them in the HTML template. Here is my search.ts file: import { localData } from ...

What could be the reason for encountering a Typescript ts(2345) error while trying to pass a mocked constant to .mockResolvedValue()?

Within my test.tsx file, I have the following code snippet: test('Photos will load', async () => { const mockCuratedPhotos = jest.spyOn(endpoints, 'getCuratedPhotos'); mockCuratedPhotos.mockResolvedValue(mockPhotos); awa ...

What steps should I take to upgrade to version 13?

My attempt to upgrade discord.js from v12 to v13 has hit a snag. Whenever I try, npm keeps reinstalling discord.js v12 instead of upgrading to v13. I've attempted deleting the node_modules folder, removing discord.js from both package.json and package ...

What is the best way to combine the attributes of multiple objects within a union type?

I have a clearly defined schema type Schema = { a: { a: 1 } b: { b: 2 } } I am in need of a function that can generate objects that adhere to multiple schemas. function createObject<K extends keyof Schema>(schema: Array<K>, obj: Sche ...

Server-capable WebPack project

Visit this page to learn about Dash, a Car simulation software available on GitHub, which I am customizing to integrate with rc-dukes as requested in this issue. The plan is to transmit the driver image to the rc-dukes software and enable control of movem ...

Issue with TypeORM Many-to-Many relation returning incorrect data when using the "where" clause

I'm facing an issue with my database tables - User and Race. The relationship between them is set as Many to Many , where a Race can have multiple Users associated with it. My goal is to retrieve all the Races that a particular user is a member of. Ho ...

VueJs with typescript encounters issues with recursive child components, resulting in a warning stating "Unknown custom element" being thrown

I am currently working on a dynamic form that is generated by a DataTypeObject (dto). I have encountered an issue with a warning message while creating recursive components. This warning points to a list of components with the same type as their parent: ...

Arranging information by utilizing arrays

I am working on a component called components.ts in my Angular project. My goal is to create a function that sorts an array based on counts, and then utilize the sorted data in my HTML to generate a chart. import { Component } from '@angular/core&apo ...

Conceal the initial value in a dropdown menu in a React component

I've set up a codesandbox to demonstrate the issue (https://codesandbox.io/s/practical-flower-k6cyl?file=/src/App.tsx) Is there a way to prevent the "AGE" text (first option) in the select box from being selected again? It should only be visible when ...

A class or another interface is the only type that an interface is allowed to extend

We are currently using typescript version 2.9.2 I encountered an issue while trying to extend the interface DropDownOption. I received the error "error TS2312: An interface may only extend a class or another interface." Is there an alternate approach to ...

Assigning dynamic key value pairs in Angular 4 using Typescript

I'm currently attempting to construct an object using keys that are specified in an environment file, meaning the keys would vary depending on the environment. import { environment } from '../environments/environment' export abstract class ...

What is the best way to create a TypeScript function that merges actions together?

I am currently working on a TypeScript function similar to the following: import multipleActionObject from page; it("should be able to perform multiple operations", () => { multipleActionObject.chooseIndex(4).setValue(10); } Inste ...