使用Webpack,React,Babel组合

时间:2017-09-20 04:10:47

标签: javascript reactjs webpack frontend babel

我一直在关注Petr Tichy(@ihatetomatoes)Webpack 2教程系列,并且已经进入this视频,其中包括安装React和Babel。

我用精细的牙齿梳理了代码并花了几个小时用谷歌搜索,但我无法让我的代码以预期的方式执行。我的app.js文件中的React方法不会执行。

应该将“Hello World”渲染到索引页面的根元素中,但我什么都没得到。

这就是我的......

./ SRC / app.js

const css = require("./styles.scss");

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
  <h1>Hello, world!</h1>,
  document.getElementById('root')
);

./ SRC / index.html中

<html>
  <head>
    <meta charset="UTF-8">
    <title><%= htmlWebpackPlugin.options.title %></title>
  <body>
      <div id="root"></div>
  </body>
</html>

webpack.config.js

const HTMLWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require('extract-text-webpack-plugin');

const path = require('path');

module.exports = {
    entry: './src/app.js',
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: 'bundle.js'
    },
    module: {
        rules: [
            { 
                test: /\.scss$/, 
                use: ExtractTextPlugin.extract( { 
                    fallback: 'style-loader', 
                    use: ['css-loader','sass-loader'] 
                } ) 
            },
            { 
                test: /\.js$/,
                exclude: /node_modules/,
                use: 'babel-loader'
            } 
        ]
    },
    plugins: [
        new HTMLWebpackPlugin({
            title: "IWTE",
            template: './src/index.html',
            minify: {
                collapseWhitespace: true,
            },
            hash: true
        }),
        new ExtractTextPlugin("styles.css")
    ],
    devServer: {
        contentBase: "./dist",
        compress: true,
        hot: true,
        open: true
    },
}

.babelrc

{
    "presets": ["es2015","react"]
}

的package.json

{
  "name": "creator",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "author": "",
  "license": "MIT",
  "private": true,
  "scripts": {
    "dev": "webpack-dev-server --progress --colors",
    "prod": "webpack -p"
  },
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-env": "^1.6.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^0.28.7",
    "eslint": "^4.7.1",
    "extract-text-webpack-plugin": "^3.0.0",
    "html-webpack-plugin": "^2.30.1",
    "node-sass": "^4.5.3",
    "sass-loader": "^6.0.6",
    "style-loader": "^0.18.2",
    "webpack": "^3.6.0",
    "webpack-dev-server": "^2.8.2"
  },
  "dependencies": {
    "react": "^15.6.1",
    "react-dom": "^15.6.1"
  }
}

非常感谢任何有关调试此问题的路线的建议或建议!我是前锋开发的亲戚。谢谢!

1 个答案:

答案 0 :(得分:2)

在package.json内部进行更改:

"scripts": {
    "dev": "webpack-dev-server --hot --progress --colors",
    "prod": "webpack -p"
}

您需要在dev命令中添加 - hot 以启用热重新加载。

如果不起作用,请告诉我。干杯!