Node.js says "ReferenceError: require is not defined" when bundling a TypeScript project with Webpack

Viewed 2416

I have a simple test.ts file which I'd like to bundle using webpack. The file contains some code and the following imports without any error:

import { from, interval, Observable, of, pipe, Subject, timer, BehaviorSubject, zip, EMPTY } from 'rxjs/index.js'
import { filter, map, mergeMap, delay, concatMap, concatMapTo, concatAll, toArray, catchError, retry, retryWhen, delayWhen, tap, take, switchMap, repeat, scan, withLatestFrom, reduce, expand, exhaustMap, mapTo } from 'rxjs/operators/index.js'
import axios from 'axios'
import cheerio from 'cheerio'
import chalk from 'chalk'

This is the content of my package.json file:

{
  "name": "myproject",
  "version": "0.0.1",
  "description": "",
  "private": "true",
  "type": "module",
  "scripts": {
    "test": "tsc && node dist/test.js",
    "build": "webpack"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/node": "^14.14.39",
    "axios": "^0.21.1",
    "chalk": "^4.1.1",
    "cheerio": "^1.0.0-rc.6",
    "rxjs": "^6.6.7",
    "telegraf": "^4.3.0"
  },
  "devDependencies": {
    "webpack": "^5.36.2",
    "webpack-cli": "^4.6.0"
  }
}

The tsconfig.json file looks like this:

{
  "compilerOptions": {
    /* Basic Options */
    "target": "ES2016",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "es2015",                          /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    "allowJs": true,                             /* Allow javascript files to be compiled. */
    "checkJs": true,                             /* Report errors in .js files. */
    "sourceMap": true,                           /* Generates corresponding '.map' file. */
    "outDir": "./dist",                          /* Redirect output structure to the directory. */
    "rootDir": "./src",                          /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */

    /* Strict Type-Checking Options */
    "strict": true,                              /* Enable all strict type-checking options. */

    /* Module Resolution Options */
    "moduleResolution": "node",                  /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    "esModuleInterop": true,                     /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */

    /* Advanced Options */
    "skipLibCheck": true,                        /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true     /* Disallow inconsistently-cased references to the same file. */
  },
  "exclude": ["./dist/**/*"]
}

When compiling the project I get the following message:

Cannot write file 'd:/asant/Desktop/myproject/webpack.config.js' because it would overwrite input file.

And this is the webpack.config.js file:

const path = require('path')

module.exports = {
    entry: './src/test.ts',
    devtool: 'inline-source-map',
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/
            }
        ]
    },
    resolve: {
        extensions: ['.tsx', '.ts', '.js']
    },
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    }
}

When the build script is run it will output:

[webpack-cli] Failed to load 'D:\asant\Desktop\myproject\webpack.config.js' config
[webpack-cli] ReferenceError: require is not defined
    at file:///D:/asant/Desktop/myproject/webpack.config.js:1:14
    at ModuleJob.run (internal/modules/esm/module_job.js:152:23)
    at async Loader.import (internal/modules/esm/loader.js:166:24)
    at async loadConfig (D:\asant\Desktop\myproject\node_modules\webpack-cli\lib\webpack-cli.js:1346:35)
    at async WebpackCLI.resolveConfig (D:\asant\Desktop\myproject\node_modules\webpack-cli\lib\webpack-cli.js:1454:38) 
    at async WebpackCLI.createCompiler (D:\asant\Desktop\myproject\node_modules\webpack-cli\lib\webpack-cli.js:1839:22)
    at async WebpackCLI.buildCommand (D:\asant\Desktop\myproject\node_modules\webpack-cli\lib\webpack-cli.js:1954:20)  
    at async Command.<anonymous> (D:\asant\Desktop\myproject\node_modules\webpack-cli\lib\webpack-cli.js:735:25)       
    at async Promise.all (index 1)
    at async Command.<anonymous> (D:\asant\Desktop\myproject\node_modules\webpack-cli\lib\webpack-cli.js:1284:13)      
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! myproject@0.0.1 build: `webpack`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the myproject@0.0.1 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\asant\AppData\Roaming\npm-cache\_logs\2021-05-01T14_28_01_191Z-debug.log
The terminal process "C:\WINDOWS\System32\cmd.exe /d /c npm run build" terminated with exit code: 2.

Also running test will output:

error TS5055: Cannot write file 'D:/asant/Desktop/myproject/webpack.config.js' because it would overwrite input file.

error TS6059: File 'D:/asant/Desktop/myproject/webpack.config.js' is not under 'rootDir' 'D:/asant/Desktop/myproject/src'. 'rootDir' is expected to contain all source files.
  The file is in the program because:
    Matched by include pattern '**/*' in 'D:/asant/Desktop/myproject/tsconfig.json'


Found 2 errors.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! myproject@0.0.1 test: `tsc && node dist/test.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the myproject@0.0.1 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\asant\AppData\Roaming\npm-cache\_logs\2021-05-01T14_29_07_580Z-debug.log
The terminal process "C:\WINDOWS\System32\cmd.exe /d /c npm run test" terminated with exit code: 1.
0 Answers
Related