Importing npm package with Webpack breaks my other code

  javascript, node.js, typescript, webpack

I’m trying to figure out why my JavaScript code is breaking. I am currently working on a TypeScript project with a simple entrypoint and loader configuration. However, when I reference any npm package in my code, it fails to run in the browser. It compiles, but doesn’t give me any error messages, not in the terminal and not in the browser console.

The transpiled code also looks fine with nothing out of the ordinary. Here is my setup:

index.ts

import _ from 'lodash'; // I tried other npm packages, too


function DomContentLoadedHandler() {
  console.log('test'); // works when line below is commented out
  console.log(_); // breaks code if uncommented
}

document.addEventListener('DOMContentLoaded', () => DomContentLoadedHandler());

webpack.config.js

const path = require('path');
const rimraf = require('rimraf');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const RemoveEmptyScriptsPlugin = require('webpack-remove-empty-scripts');
const outputPath = path.resolve(__dirname, '..', '..', 'wwwroot', 'build');
rimraf.sync(outputPath);

module.exports = {
    entry: {
        main: './source/scripts/index.ts'
    },
    resolve: {
        extensions: ['.ts', '.js'],
        plugins: [new TsconfigPathsPlugin()],
    },
    output: {
        path: outputPath,
        filename: '[name].bundle.js',
    },
    optimization: {
        chunkIds: 'named',
        runtimeChunk: 'single',
        splitChunks: {
            chunks: 'all',
            automaticNameDelimiter: '-',
        },
    },
    plugins: [
        new RemoveEmptyScriptsPlugin(),
        ...
    ],
    watchOptions: {
        ignored: /node_modules/
    },
    devtool: 'source-map',
    module: {
        rules: [
            {
                test: /.(js|ts)$/,
                use: 'babel-loader'
            },
        ]
    }
};

tsconfig.json:

{
  "compilerOptions": {
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "CommonJS",
    "moduleResolution": "node",
    "target": "ES5",
    "strictNullChecks": true,
    "strict": true,
    "allowSyntheticDefaultImports": true,
    "baseUrl": ".",
    "skipLibCheck": true,
    "paths": {
      "@src/*": [ "source/*" ]
    }
  }
}

I think I’ve literally done this same exact thing like a million times so I’m really lost as to what is happening. I’ve tried switching to ts-loader, but to no avail. Tried re-installing node_modules several times, clearing npm cache, etc.

Any help would be greatly appreciated. Thanks in advance!

Source: Ask Javascript Questions

LEAVE A COMMENT