【问题标题】:Webpack: ReferenceError: document is not defined [closed]Webpack:ReferenceError:文档未定义[关闭]
【发布时间】:2020-02-26 00:12:50
【问题描述】:

我正在从头开始创建 React 应用程序。在某些时候,我在使用 webpack 构建我的应用程序时遇到了类似标题中的错误。

Here is a minimal repository to reproduce this error.

有什么问题,我该如何解决这个错误?

【问题讨论】:

  • 当您对问题投反对票时,请评论原因
  • 我确实赞成...

标签: javascript node.js reactjs webpack ecmascript-6


【解决方案1】:

我之前提交的代码没有运行,但这在浏览器中运行并为您提供了 hello world。 我已经安装了名为ejs-loader 的额外包 (由于 ejs 扩展,我猜,它没有得到文档节点) 这是你的 webpack 配置 已更新

const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");

var config = {
  entry: "./src/index.tsx",

  output: {
    path: path.join(__dirname, "/dist"),
    filename: "bundle.min.js"
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: "Showcase",
      template: "./src/index.ejs",
      inject: true,
      filename: "./index.html"
    })
  ],

  resolve: {
    extensions: [".ts", ".tsx", ".js"]
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        loader: "ts-loader",
        include: [path.resolve(__dirname, "src")],
        exclude: /node_modules/
      },
      { test: /\.ejs$/, loader: "ejs-loader?variable=data" }
    ]
  },
  optimization: {
    splitChunks: {
      cacheGroups: {
        vendors: {
          priority: -10,
          test: /[\\/]node_modules[\\/]/
        }
      },

      chunks: "async",
      minChunks: 1,
      minSize: 30000,
      name: true
    }
  }
};
module.exports = config;

这是您的 tsconfig 已更新

{
  "compilerOptions": {
    "sourceMap": true,
    "noImplicitAny": false,
    "module": "commonjs",
    "outDir": "./dist/",
    "target": "es6",
    "lib": ["es2015", "es2017", "dom"],
    "removeComments": true,
    "allowSyntheticDefaultImports": false,
    "jsx": "react",
    "allowJs": true,
    "baseUrl": "./",
    "paths": {
      "components/*": ["src/components/*"]
    }
  }
}

只需在你的根目录中创建一个 dist 文件夹

【讨论】:

  • 它确实有效,现在我必须弄清楚我的初始配置中出了什么问题。谢谢。
  • 好的,很高兴听到:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
  • 2016-05-06
  • 2020-10-26
  • 2015-11-14
  • 2019-11-28
相关资源
最近更新 更多