我在我的新Reactjs应用程序上收到404错误,是否正在寻找main.js文件?

时间:2016-08-22 01:55:34

标签: javascript reactjs webpack babel-core

这个应用程序应该渲染我在这里(/Users/ldco2016/Projects/reactquiz/src/components/App.jsx:

import React, {Component} from 'react';
import ReactDOM from 'react-dom';

class App extends Component{
    render(){
        return(
            <div>
                APP
            </div>
        )
    }
}

export default App

但我得到一个空白页面,Chrome Dev工具控制台告诉我这个:

GET http://localhost:8080/app/js/main.js 404 (Not Found)

我知道这意味着什么,但我不清楚它是否正在尝试查找我要渲染的页面或main.js文件。

/Users/ldco2016/Projects/reactquiz/package.json:

{
  "name": "reactquiz",
  "version": "1.0.0",
  "description": "A Reactjs Quiz App",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Daniel Cortes",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "6.13.*",
    "babel-loader": "6.2.*",
    "webpack": "1.13.*"
  },
  "dependencies": {
    "react": "^15.3.1",
    "react-dom": "^15.3.1"
  }
}

/Users/ldco2016/Projects/reactquiz/app/index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Reactjs Quiz</title>
</head>
<body>
    <div id="app"></div>

    <script src="js/main.js"></script>
</body>
</html>

ldco2016 @ DCortes-MacBook-Pro-3~ / Projects / reactquiz / webpack.config.js:

module.export = {
    entry: [
        './src/index.js'
    ],
    output: {
        path: __dirname,
        filename: 'app/js/main.js'
    },
    module: {
        loaders: [{
            test: /\.jsx?$/,
            loader: 'babel',
            exclude: /node_modules/
        }]
    }

}

/Users/ldco2016/Projects/reactquiz/src/index.js:

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

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

1 个答案:

答案 0 :(得分:1)

您需要运行webpack来生成main.js文件。首先在package.json添加脚本"start": "webpack --progress -p --config webpack.config.js --watch"并在webpack.config.js中将加载程序更改为babel-loader,对文件进行两处更改。

P.S。可能不需要进行第二次更改。

<强>的package.json

{
  "name": "reactquiz",
  "version": "1.0.0",
  "description": "A Reactjs Quiz App",
  "main": "index.js",
  "scripts": {
    "start": "webpack --progress -p --config webpack.config.js --watch"
  },
  "author": "Daniel Cortes",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "6.13.*",
    "babel-loader": "6.2.*",
    "webpack": "1.13.*"
  },
  "dependencies": {
    "react": "^15.3.1",
    "react-dom": "^15.3.1"
  }
}

<强> webpack.config.js

module.export = {
    entry: [
        './src/index.js'
    ],
    output: {
        path: __dirname,
        filename: 'app/js/main.js'
    },
    module: {
        loaders: [{
            test: /\.jsx?$/,
            loader: 'babel-loader',
            exclude: /node_modules/
        }]
    }

}

现在使用命令

运行webpack
npm run start

现在打开你的localhost,上面应该可以工作。