How to only compile one typescript file with webpack 5 and exclude everything else?

Viewed 568

I have a Node.js runtime that is serving a react app.

the full source can be found here, here is the folder structure: enter image description here

I run npm run build from within react-app to compile the react app itself.

Then I want to run npm run build from the root of the project to compile ONLY index.ts file to /dist/index.js, and IGNORE the stuff in react-app folder.

Here is my webpack.config.ts:

const webpack = require("webpack");
const path2 = require("path");
const nodeExternals = require("webpack-node-externals");
const copyFiles = require('copy-webpack-plugin');

module.exports = {
    entry: './index.ts',
    target: "node",
    mode: "production",
    externals: [nodeExternals()],
    resolve: {
        extensions: ['.ts']
    },
    module: {
        rules: [
            // all files with a `.ts` extension will be handled by `ts-loader`
            { test: /index.ts$/, loader: 'ts-loader', exclude: [ path2.resolve(__dirname, 'react-app')]}
        ]
    },
    plugins: [new webpack.HotModuleReplacementPlugin(), new copyFiles({ patterns: [{ from: 'react-app/build', to: 'build'}]})],
    output: {
        path: path2.resolve(__dirname, 'dist'),
        filename: 'index.js'
    },
};

I've tried only including the index.ts file and excluding the react-app folder in a million ways, but webpack keeps trying to compile the ts files in the react-app folder. enter image description here

Here is my package.json:

{
  "name": "frontend-service",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node dist/index.js",
    "build": "webpack",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  },
  "devDependencies": {
    "@types/express": "^4.17.11",
    "@types/node": "^14.14.31",
    "copy-webpack-plugin": "^7.0.0",
    "ts-loader": "^8.0.17",
    "ts-node": "^9.1.1",
    "typescript": "^4.2.2",
    "webpack": "^5.24.2",
    "webpack-cli": "^4.5.0",
    "webpack-node-externals": "^2.5.2"
  }
}

Please help.

1 Answers

I first thought Keith's comment was wrong because I added the "include": ["index.ts"] to the "compileOptions" of my tsconfig and got:

error TS5023: Unknown compiler option 'include'.

But apparently I had to put it outside of the compileOptions like:

{
  "compilerOptions": {
    // Your options.....
  },
  "include": ["./index.ts"]
}

And that works!

However, the react project won't build anymore because it finds:

a different version of webpack-dev-server was detected higher up in the tree

I recommend to not put the react typescript project in a node typescript project. It's probably better to create a root folder and put the react project in a folder next to the node project.

Related