【问题标题】:How to display console.logs using Webpack build?如何使用 Webpack 构建显示 console.logs?
【发布时间】:2020-08-30 17:48:03
【问题描述】:

我正在使用 Webpack 构建一个 React 应用程序。我正在尝试使用console.log 进行调试,但它们没有出现在浏览器控制台或终端中。这似乎并没有太多的内容(我在这方面发现的唯一另一个问题是:Webpack console.log output?

webpack.config.js

const path = require('path');
const webpack = require('webpack');

module.exports = {
  entry: './src/App.tsx',
  mode: 'development',
  module: {
    rules: [
      { 
        test: /\.(|ts|tsx|js|jsx)$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [
              '@babel/preset-env',
              '@babel/preset-react',
              '@babel/preset-typescript',
            ],
            plugins: [
              '@babel/plugin-proposal-class-properties',
            ],
          },
        },
      },
      {
        test: /\.(css|scss)$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.(jpe?g|gif|png|svg)$/i,
        loader: 'url-loader',
        options: {
          limit: 25000,
          esModule: false,
        },
      },
    ],
  },
  resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx'] },
  output: {
    path: path.resolve(__dirname, 'dist/'),
    publicPath: '/dist/', 
    filename: 'bundle.js',
  },
  devServer: {
    contentBase: path.join(__dirname, 'public/'),
    port: 3000,
    publicPath: 'http://localhost:3000/dist/',
    hot: true,
  },
  plugins: [new webpack.HotModuleReplacementPlugin()],
};

App.tsx

import React from 'react';
import { render } from 'react-dom';
import Hello from './Hello';

console.log('test1') // this gets logged

render(<Hello />, document.querySelector('#main'));

你好.tsx

import React, { RefObject } from 'react';

interface Props { }

interface State { }

console.log('test2') // this gets logged 

export default class Hello extends React.Component<Props, State> {

  private start() {
    console.log('test3') // this doesn't get logged 
  }

  constructor(p: Props) {
    super(p);
    this.start();
    console.log('test4') // this gets logged 
  }
}

感谢任何见解!

【问题讨论】:

    标签: reactjs webpack


    【解决方案1】:

    我认为问题可能出在您设置contentBase 的位置与构建文件夹不同,因此您手动创建的模板无法加载您构建的脚本。

    我的建议是将index.html 和您构建的文件放在同一个目录中。我建议使用插件html-webpack-plugin,它可以帮助您将template 复制到构建文件夹中+ 注入脚本文件。假设您将使用包含哈希的名称构建项目以避免缓存,您如何自动注入构建的文件?所以只要你添加这个包+删除你的contentBase配置,那么它就可以正常工作了。

    【讨论】:

      猜你喜欢
      • 2017-04-23
      • 1970-01-01
      • 1970-01-01
      • 2022-08-04
      • 2022-06-23
      • 1970-01-01
      • 1970-01-01
      • 2014-04-08
      • 2017-10-29
      相关资源
      最近更新 更多