27

I'm building a TS library bundled with Webpack 5.3.2. I then try to load the output bundle, dist/scalextric.js, into a node.js script:

node -e 'console.dir(Object.keys(require("./dist/scalextric.js")));'

I get:

ReferenceError: self is not defined
    at Object.<anonymous> (/media/kratib/Data/src/infojunkie/scalextric/dist/scalextric.js:2:215)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at [eval]:1:25
    at Script.runInThisContext (vm.js:132:18)
    at Object.runInThisContext (vm.js:309:38)

I need help fixing this error. Here are my various configs:

  • webpack.config.js:
const path = require('path');

module.exports = {
  entry: './src/index.ts',
  devtool: 'inline-source-map',
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: [ '.tsx', '.ts', '.js' ],
  },
  output: {
    filename: 'scalextric.js',
    library: 'Scalextric',
    libraryTarget: 'umd',
    path: path.resolve(__dirname, 'dist'),
    umdNamedDefine: true,
  },
};
  • tsconfig.json:
{
  "compilerOptions": {
    "module": "commonjs",
    "lib": ["dom", "esnext.asynciterable"],
    "target": "es6",
    "moduleResolution": "node",
    "outDir": "./dist",
    "sourceMap": true,
    "declaration": true,
    "importHelpers": true
  },
  "include": [
    "src"
  ]
}
  • index.ts:
export * from './Tuning';
export * from './TuningNotation';
export * from './Interval';

Any obvious mistake I am making? Here's the full code.

2 Answers 2

69

This issue is related to the option output.globalObject of which is described here.

I believe webpack has set it as self for a certain reason. But in order to work on browser and node you can simply switch to this:

output: {
  // ...
  globalObject: 'this',
},

Sign up to request clarification or add additional context in comments.

Comments

0

I solve my issye against ReferenceError: self is not defined at__webpack_require__

const MyComponent = dynamic(() => import('../components/MyComponent'), { ssr: false });

Just false your SSR component where you're getting the error...

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.