0

I have a monorepo that includes both a front-end (CRA) React app and an Express API. They both use another package in the monorepo that is plain TS, but uses import statements. I use tsc to compile the TS -> JS for the React app, into a directory I call tscompiled, and for the Node app I further transpile the JS with babel to a directory called lib, so that all the import statements become requires.

So when I want to compile the React app, I need package.json for my dependency to use the tscompiled directory with its type definitions:

"main": "tscompiled/index.js",

And then when I want to compile the Express app, I need package.json for my dependency to use the lib directory:

"main": "lib/index.js",

This is a real kludge — can I get my Node Express app to handle import statements or transpile dependent packages within the monorepo automatically?

ed94133
  • 1,477
  • 2
  • 19
  • 40

2 Answers2

0

You should be able to use imports if you configure your project correctly. See the solutions mentioned in this SO thread.

david-err
  • 1,037
  • 1
  • 8
  • 12
  • This has gotten me a certain part of the way there, but I'm running up against a new problem — I use require for a number of json files, but once I set `"type": "module"`, I can't use require. Yet as far as I can tell import for json files is not available yet. – ed94133 Sep 23 '21 at 20:09
0

I found a good solution for this problem, which was to use webpack for my Express API, with babel taking care of compiling TS and transpiling ES in dependent modules.

.babelrc:

{
    "presets": ["@babel/preset-env", "@babel/preset-typescript"]
}

webpack.config.js:

const path = require('path')
const nodeExternals = require('webpack-node-externals')

module.exports = {
    mode: 'production',
    entry: path.resolve(__dirname, 'src') + '/index.ts',
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: '[name].js',
    },
    module: {
        rules: [
            {
                test: /\.(ts|tsx|jsx|js)x?$/,
                use: {
                    loader: 'babel-loader'
                },
                exclude: /node_modules/,
            },
        ],
    },
    resolve: {
        extensions: ['.ts', '.tsx', '.js', '.json', '.helpers.js'],
        mainFields: ['main'],
    },
    target: 'node',
    externals: [nodeExternals()]
}
ed94133
  • 1,477
  • 2
  • 19
  • 40