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.
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',
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With