Stefdelec
Stefdelec

Reputation: 2811

Webpack error for a very simple typescript project

I am trying to build a very simple library in typescript. It should be use-able on browsers or node. So platform agnostic.

I've got this error when I launch node ./dist/bundle.js:

ReferenceError: self is not defined at eval (webpack:///./node_modules/oboe/dist/oboe-browser.js?:2701:10)

I tried a very simple configs :

const path = require('path');

module.exports = {
    mode: 'development',
    entry: './src/index.ts',
    watch: true,
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/
            }
        ]
    },
    resolve: {
        extensions: ['.tsx', '.ts', '.js']
    },
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    }
};

And ts :

{
  "compilerOptions": {
    "outDir": "./dist",
    "noImplicitAny": false,
    "sourceMap": true,
    "target": "es6",
    "allowJs": true,
    "lib": [
      "es5",
      "es2017"
    ],
    "baseUrl": "src",
    "resolveJsonModule": true,
    "module": "commonjs"
  },
  "exclude": [
    "src/**/*.test.ts"
  ]
}

I don't understand what configs I should do.

And if I use tsc directly it throw another error.

Upvotes: 0

Views: 86

Answers (1)

Nathan
Nathan

Reputation: 8141

I believe this is an issue with how you're trying to access the bundle: node ./dist/bundle.js By default webpack targets the 'web' environment yet this line of code is trying to use the generated JavaScript bundle with node. According to the documentation:

"Because JavaScript can be written for both server and browser, webpack offers multiple deployment targets that you can set in your webpack configuration... each target has a variety of deployment/environment specific additions, support to fit its needs"

Try adding a node target specification within your webpack.config.js:

const path = require('path');

module.exports = {
    mode: 'development',
    entry: './src/index.ts',
    watch: true,
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/
            }
        ]
    },
    resolve: {
        extensions: ['.tsx', '.ts', '.js']
    },
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    },
    target: 'node'
};

Hopefully that helps!

Upvotes: 1

Related Questions