Typescript + Webpack 库生成“ReferenceError: self is not defined"; [英] Typescript + Webpack library generates "ReferenceError: self is not defined"

查看:158
本文介绍了Typescript + Webpack 库生成“ReferenceError: self is not defined";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个与 Webpack 5.3.2 捆绑在一起的 TS 库.然后我尝试将输出包 dist/scalextric.js 加载到 node.js 脚本中:

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")));'

我明白了:

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.

      推荐答案

      此问题与 output.globalObject 选项有关,其中 在此处描述.

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

      我相信 webpack 出于某种原因将其设置为 self.但是为了在浏览器和节点上工作,你可以简单地切换到 this:

      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',
      },
      
      

      这篇关于Typescript + Webpack 库生成“ReferenceError: self is not defined";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆