从零搭建react16开发环境(二)——react

安装React

命令行输入并执行:cnpm install react react-dom --save

安装Babel

通过Babel来使代码支持ES语法以及React语法。
命令行输入并执行:npm install --save-dev babel-loader babel-core babel-preset-env babel-preset-react
根目录下创建.babelrc文件,写入配置信息

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

修改webpack.base.conf.js文件

// webpack.base.conf.js
const path = require('path');
const APP_PATH = path.resolve(__dirname, '../src');
const DIST_PATH = path.resolve(__dirname, '../dist');
module.exports = {
    entry: {
        app: './src/index.js'
    },    
    output: {
        filename: 'js/bundle.js',
        path: DIST_PATH
    },
    module: {
        rules: [
            {
                test: /\.js?$/,    //对于js使用babel编译成es5
                use: "babel-loader",
                include: APP_PATH
            }
        ]
    }
};

在src/index.js文件使用react

import React from "react";
import ReactDom from "react-dom";

ReactDom.render(
    <h1>hello, world!</h1>,
    document.getElementById("root")
);

这时候运行npm run build即可打包
然后在我的打包过程中出现如下图错误提示:

image.png

根据提示重新安装了babel-loader@7,最终打包成功。

安装HtmlWebpackPlugin

打包好的js需要我们手动在html引入才可使用,通过webpack中的HtmlWebpackPlugin即可实现自动引入。
命令行输入并执行:npm install --save-dev html-webpack-plugin
在webpack.prod.conf.js引入

// webpack.prod.conf.js
const merge = require('webpack-merge'); //合并
const baseWebpackConfig = require('./webpack.base.conf');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = merge(baseWebpackConfig, {
    mode: 'production',  //webpack4新增mode,"production" | "development" | "none"
    plugins: [
        new HtmlWebpackPlugin({
              template: 'index.html',
              minify: {
                removeComments: true,     // 移除HTML中的注释
                collapseWhitespace: true, // 删除空白符与换行符
              },
         }),
    ]
});
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容