【问题标题】:Unable to load ReactJS resource in the browser using Babel and Webpack无法使用 Babel 和 Webpack 在浏览器中加载 ReactJS 资源
【发布时间】:2016-12-01 02:51:24
【问题描述】:

我正在尝试通过运行一个基本程序来学习 ReactJS。

webpack.config.js

var config = {
    entry: './main.js',

    output: {
        path: './',
        filename: 'index.js'
    }, 

    devServer: {
        inline: true,
        port: 8080
    }, 

    module: {
        loaders: [
            {
                test: /\.jsx?$/, 
                exclude: /node_modules/,
                loader: 'babel-loader',

                query: {
                    presets: ['es2015', 'react']
                }
            }
            ]
    }
}

module.experts = config;

package.json

{
  "name": "reactapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server --hot"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "babel-core": "^6.11.4",
    "babel-loader": "^6.2.4",
    "babel-preset-es2015": "^6.9.0",
    "babel-preset-react": "^6.11.1",
    "react": "^15.2.1",
    "react-dom": "^15.2.1",
    "webpack": "^1.13.1",
    "webpack-dev-server": "^1.14.1"
  }
}

App.jsx

import React from 'react';

class App extends React.Component   {
    render()    {
    return  (
    <div>
        "Hello, world."
    </div>
    );
    }
}

export default App;

main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';

ReactDOM.render(<App />, document.getElementById('app'));

index.html

<!DOCTYPE html>
<html lang = "en">
<head>
    <meta charset="utf-8">
    <title>React App</title>
</head>
<body>
    <div id = "app"></div>
    <script type="text/javascript" src = "index.js"></script>
</body>
</html>

在启动服务器时,我看到一个没有内容的空白页面。 HTML 页面在那里,但看不到 React 要添加到 DOM 的部分。

index.js 被设置为将包含我们捆绑的应用程序的文件,但浏览器的控制台显示“加载资源 index.js(404) 失败”错误。如果我将 HTML 中 script 标签的 src 属性更改为 main.js,我会在 import 语句中得到一个 SyntaxError。

我怀疑问题出在我的包中没有正确链接 Babel 或其他一些依赖项。

【问题讨论】:

    标签: javascript reactjs webpack


    【解决方案1】:

    webpack.config.js 里面有错字,必须是 exports 而不是 experts

    module.exports = config;
              ^
    

    在这种情况下,您不会从webpack.config.js 导出配置,而webpack 不知道您的自定义配置并使用默认配置。

    【讨论】:

      【解决方案2】:

      我认为webpack.config.js会像

      devtool: 'eval',
      entry: './src/index',
      output: {
        path: path.join(__dirname, 'dist'),
        filename: 'bundle.js',
        publicPath: '/static/',
      },
      module: {
        loaders: [{
          test: /\.js$/,
          loaders: ['babel'],
          exclude: /node_modules/,
          include: __dirname,
        }],
      }
      

      还有&lt;script&gt;

      <script type="text/javascript" src = "/static/bundle.js"></script>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-04-02
        • 2017-12-27
        • 2022-10-30
        • 2017-01-05
        • 2019-03-07
        • 1970-01-01
        • 2020-07-01
        • 1970-01-01
        相关资源
        最近更新 更多