gayashanbc
gayashanbc

Reputation: 1024

javascript- ReferenceError: require is not defined

I'm trying to bundle and run a TypeScript project using Webpack. One of the TypeScript files requires and external node depenedency. Webpack bundles the file without problem, but when I try to run it on the browser it gives me the following error.

Error message

webpack.config.js

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

module.exports = {
  entry: './src/index.ts',
  resolve: {
    extensions: [
      '.js',
      '.jsx',
      '.json',
      '.ts',
      '.tsx'
    ]
  },
   externals: [nodeExternals()],
  output: {
    libraryTarget: 'commonjs',
    path: path.join(__dirname, '.webpack'),
    filename: '[name].js',
  },
  target: 'web',
  module: {
    loaders: [
      { test: /\.ts(x?)$/, loader: 'ts-loader' },
    ],
  },

};

External node dependency aws-iot-device-sdk

Can someone help me with this?

Update: Found that the following line in the TypeScript file causes the issue. is there a work-around for this?

const client = new IoTClient(true, IoTClientOptions);

Upvotes: 3

Views: 2680

Answers (2)

gayashanbc
gayashanbc

Reputation: 1024

The following Webpack configuration solved my issue.

const path = require('path');

module.exports = {
  entry: {
    chatUI: './src/chat-ui.ts',
    chatLogic: './src/chat-logic.ts',
  },
  resolve: {
    extensions: [
      '.js',
      '.jsx',
      '.json',
      '.ts',
      '.tsx'
    ]
  },
  output: {
    path: path.join(__dirname, '.webpack'),
    filename: '[name].js',
  },
  node: {
    fs: 'empty',
    tls: 'empty'
  },
  target: 'web',
  module: {
    loaders: [
      {
        test: /\.tsx?$/,
        loader: 'awesome-typescript-loader'
      }
    ],
  },

};

Upvotes: 1

SF..MJ
SF..MJ

Reputation: 880

As you are using

require('path');

you have to download RequireJS

Here

RequireJS is a JavaScript file and module loader.

or add Add http://requirejs.org/docs/release/2.2.0/minified/require.js to your project

Upvotes: 1

Related Questions