【问题标题】:Webpack not bundling node modules imported in dependency JS filesWebpack 不捆绑在依赖 JS 文件中导入的节点模块
【发布时间】:2016-07-06 07:18:58
【问题描述】:

我正在使用 Webpack 来捆绑我的 ReactJS 应用程序。

helloworld.js

import React from 'react';

export default class HelloWorld extends React.Component {
    render() {
        return <h2>Hello {this.props.name}!</h2>;
    }
}

index.js

import ReactDOM from 'react-dom';
import HelloWorld from './helloworld';

ReactDOM.render(<HelloWorld name="World" />,
    document.getElementById('container'));

webpack.config.js

module.exports = {
    entry: './index.js',
    output: 'bundle.js',
    module: {
        loaders: [
            {
                test: /(\.js|\.jsx)/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    presets: ['es2015', 'react']
                }
            }
        ]
    }
};

当我运行webpack-dev-server --progress --colors 时,我在浏览器中遇到错误“React 未定义”,但如果我直接在 index.js 中导入 React,则不会出现错误。 如果在 helloworld.js 文件中引用了 React,为什么 Webpack 不将 React 包含在包中?

【问题讨论】:

    标签: reactjs webpack webpack-dev-server


    【解决方案1】:

    好吧,webpack 只是通过读取其中的依赖项并解析它们以呈现特定元素来尝试捆绑各个模块。现在在捆绑

    ReactDOM.render(<HelloWorld name="World" />,
        document.getElementById('container'));
    

    ReactDOM 尝试执行 React.createElement(_Helloworld2.default, { name: 'World' }), document.getElementById('app') 函数,该函数需要 React 作为你的 index.js 文件中不存在的依赖项,因此当你在 index.js 文件中 import React 时它会给出错误并解决问题。希望我能解释一下,我的回答对你有帮助。

    【讨论】:

      【解决方案2】:

      您缺少import React from 'react'; 声明。 每次在文件中编写 JSX 时都会用到它,因为它会转换为 React.createElement(..) 函数调用。

      【讨论】:

        猜你喜欢
        • 2022-01-03
        • 2021-11-30
        • 1970-01-01
        • 2021-11-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-11
        • 2020-11-17
        相关资源
        最近更新 更多