1

I have a question for you - how is it possible to implement multi-file compilation while preserving the tree of folders and documents, while not writing each file into entry in this way

entry: {
    index:'./src/index.ts',
    'bot/main':'./src/bot/main.ts'
  }

But at the same time, the files had their names and their position, as before compilation in js, only instead of the src folder, they were in the dist folder?

My current config webpack.config.js

const path = require('path')
const nodeExternals = require('webpack-node-externals')
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin')

module.exports = {
  context: __dirname,
  entry: {
    index:'./src/index.ts',
    'bot/main':'./src/bot/main.ts'
  },
  externals: [nodeExternals()],
  module: {
    rules: [
      {
        exclude: /node_modules/,
        test: /.ts$/,
        use: {
          loader: 'ts-loader'
        }
      }
    ]
  },
  node: {
    __dirname: false
  },
  resolve: {
    extensions: ['.ts', '.js'],
    plugins: [
      new TsconfigPathsPlugin({
        baseUrl: './src'
      })
    ]
  },
  output: {
    filename: '[name]js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/dist/'
  },
  target: 'node'
}

And when building in production mode, all this was compiled into one file, taking into account all URLs, imports, etc.

Is it even possible?

1 Answer 1

1

Webpack itself won't do that for you. You will need to write litter helper function to achieve this. The basic idea is to crawl the directory, find all the files and then provide them to Webpack:

const path = require('path');
const glob = require('glob');


const extension = 'ts';

// Recursively find all the `.ts` files inside src folder.
const matchedFiles = glob.sync(`./src/**/*.${extension}`, {
  nodir: true
});

const entry = {};

matchedFiles.forEach((file) => {

  const SRC_FOLDER = path.join(__dirname, 'src');
  const ABS_PATH = path.join(__dirname, file);

  // Generates relative file paths like `src/test/file.ts`
  const relativeFile = path.relative(SRC_FOLDER, ABS_PATH);
  
  // fileKey is relative filename without extension.
  // E.g. `src/test/file.ts` becomes `src/test/file`
  const fileKey = path.join(path.dirname(relativeFile), path.basename(relativeFile, extension));

  entry[fileKey] = relativeFile;
});


module.exports = {
  context: __dirname,

  // Use the entry object generated above.
  entry,
  // ... rest of the configuration
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.