Webpack 3.x 通过webpack安装React和Babel

之前用最原始的方式写过一个React的hello world,参见:原始React hello world

在React的官网上面会介绍好几种方式去安装React,下面尝试通过Webpack来安装:

npm i -D react react-dom

安装完成后的版本:

"react": "^16.1.1",
"react-dom": "^16.1.1",

在使用React的时候,必须要熟悉ES6与Babel,官网上面对它的介绍:Enabling ES6 and JSX

  • JSX:(JavaScript XML)是一种嵌入式的类似XML的语法。 它可以被转换成合法的JavaScript,要解析它的话,就要用到Babel,Babel是一个JS compiler, seems 专为React而生,还不能确定别的地方有没有用到过Babel。先安装Babel:
npm i -D babel babel-preset-react babel-preset-es2015 babel-preset-env

安装完成后,在package.json中看到它的版本:

"babel-preset-env": "^1.6.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",

需要创建一个.babelrc文件,并code like below ,才可以正常运行:

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

将下面的代码添加到app.js中:

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

ReactDOM.render(
  

Hello, webpack react!

, document.getElementById('root') );

在模板my-index.html中相应的也添加一个id为root的div:

<div id="root">div>

重新build,感觉可以看到React页面了,其实出错了,从terminal 的log中可以看到JSX被编译失败了:

➜  WebPack110 npm run dev

> webpack-stater@1.0.0 dev /Users/Stan/Desktop/WebPack110
> webpack-dev-server

Project is running at http://localhost:9000/
webpack output is served from /
Content not from webpack is served from /Users/Stan/Desktop/WebPack110/dist
webpack: wait until bundle finished: /

ERROR in ./src/app.js
Module parse failed: Unexpected token (7:2)
You may need an appropriate loader to handle this file type.
|
| ReactDOM.render(
|   <h1>Hello, webapck react!</h1>,
|   document.getElementById('root')
| );
 @ multi (webpack)-dev-server/client?http://localhost:9000 ./src/app.js
webpack: Failed to compile.

原因是对于babel的设置还没有结束,得需要安装一个babel loader , 参考这里install babel-loader,build systems 中选择webpack:

npm install --save-dev babel-loader babel-core

安装完成后在package.json中看到它的版本:

"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",

再在modules对象的rules中添加一个新的rule:

module: {
        rules: [
          { test: /\.scss$/, 
            use: ExtractTextPlugin.extract({
              fallback:"style-loader",
              use: ['css-loader','sass-loader'],
              publicPath: "/dist",
            })},
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: "babel-loader"
            }
            //['style-loader','css-loader','sass-loader']
        ]
    }

再重新去build,这个时候就可以正常的解析JSX了,页面正常显示出来:

你可能感兴趣的:(webpack3-x)