问题
I'm new to React and I followed Facebook's Installation (Create a New App).
So every time I need to run the app, it needs to start a server. When I try to open the build version in chrome( opening HTML directly ), nothing gets displayed.
Then I tried to setup React environment myself from scratch using codecademy tutorial. Here, after I build the project, I can directly open the HTML in chrome and the contents are displayed.
My question is:
Why webpage doesn't get displayed in the 1st method but 2nd method runs without starting server?
Edit:
package.json for 2nd method:
{
"name": "practice",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"start": "webpack-dev-server"
},
"author": "",
"license": "ISC",
"dependencies": {
"react": "^15.6.1",
"react-dom": "^15.6.1"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "^2.30.1",
"webpack": "^3.6.0",
"webpack-dev-server": "^2.8.2"
}
}
webpack.config.js:
var HTMLWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HTMLWebpackPlugin({
template: __dirname + '/app/index.html',
filename: 'index.html',
inject: 'body'
});
module.exports = {
entry: __dirname + '/app/index.js',
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
]
},
output: {
filename: 'transformed.js',
path: __dirname + '/build'
},
plugins: [HTMLWebpackPluginConfig]
};
回答1:
The problem is: path to the other files in the HTML.
When the webpack-dev-server
is run from the directory, it assumes it is the root of the server.
So, if you open your app's HTML(build/index.html
) created with Facebook tutorial, you can see that the path to other files are given as absolute path but not as a relative path.
Like in HTML you can see /static/pathToFile
but not ./static/pathToFile
.
So, according to your 2nd method, try to give the path to transformed.js
as /transformed.js
in your HTML. It doesn't display anything. But if you run npm run start
and then open your localhost with given port number(just like in the 1st method). Now you can see your React app.
Opinion: Always try to setup your environment by yourself from scratch. Don't try easy to setup methods like Facebook's "create new app". Instead try Facebook's "Adding React to an Existing Application". You can learn how things actually work, like today.
Tip:
Try to debug the app always in your web browser!
For example, open your 1st method HTML in your chrome and open developer tools.
Head over to the network tab and reload.
Hover-over the failed file to see what is the error. You can see ERR_FILE_NOT_FOUND
.
Click on it to see return status, url requested etc.
Hope it helps!
来源:https://stackoverflow.com/questions/46340753/why-react-needs-webpack-dev-server-to-run