【问题标题】:"Uncaught ReferenceError: exports is not defined" in HTML5 boilerplateHTML5 样板中的“未捕获的 ReferenceError:未定义导出”
【发布时间】:2018-10-01 11:51:33
【问题描述】:

我在 WebStorm 中创建了一个 HTML5 Boilerplate 项目。当我想运行它时,我使用localhost:8080/myproject/src URL。在src 文件夹中,我有一个js 文件夹,其结构如下:

libraries
models
    place.model.ts
      place.model.js
    address.model.ts
      address.model.ts
main.ts
  main.js

Typescript 编译器将 .ts 文件转换为 .js

在我的 .model.ts 文件中,我有以下代码:

export class MyClass {
    x: string;
    constructor(x: string) {
        this.x = x;
    }
}

然后在我的 main.ts 中导入它:

import {MyClass as My} from "./models/myclass.model";

当我尝试运行 URL 时 - 我收到了这个错误:Uncaught ReferenceError: exports is not defined。我查看编译后的 main.js 文件,看到添加了这一行:

Object.defineProperty(exports, "__esModule", { value: true });

我试图通过在我的 index.html 文件中插入以下脚本来解决它:

<script>var exports = {};</script>

但后来我收到此错误消息:ReferenceError: require is not defined

我缺少什么以及如何让它发挥作用?

更新 该项目最初没有tsconfig文件,所以我手动添加了一个。内容如下:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "sourceMap": false
  },
  "exclude": [
    "node_modules"
  ]
}

我在没有"module": "commonjs" 的情况下尝试过,但没有帮助。

【问题讨论】:

  • 请分享你的 tsconfig.json
  • 您需要为浏览器准备代码。你使用 webpack 或 browserify 还是其他的?
  • 也许你应该先检查一下stackoverflow.com/questions/45112655/…
  • @GrzegorzMotyl 我用 tsconfig 部分更新了问题。谢谢!
  • @Drag13 不,不使用任何。不幸的是,不熟悉它们,认为样板应该“按原样”工作。检查链接,谢谢!

标签: javascript typescript


【解决方案1】:

看起来当我第一次尝试使用 Webpack 时,我使用了旧版本的配置。一旦我更改了配置 - 一切都按预期工作。我还能够为 .ts 文件更改配置一个观察者。

const path = require('path');

module.exports = {
  entry: './src/js/main',
  mode: 'development',
  watch: true,
  watchOptions: {
    aggregateTimeout: 600,
    poll: 1000,
    ignored: /node_modules/
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        loader: 'ts-loader'
      }
    ]
  },
  resolve: {
    extensions: ['.webpack.js', '.web.js', '.ts', '.js', '.tsx', '.json']
  },
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, './src/js')
  }
}

【讨论】:

    猜你喜欢
    • 2018-02-20
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 2019-02-28
    • 1970-01-01
    • 1970-01-01
    • 2023-01-23
    • 2016-04-26
    相关资源
    最近更新 更多