webpack4+babel7安装

webpack4+babel7安装

  • 前言
  • 1. package.json
  • 2. webpack.config.js
  • 3. .babelrc
  • 4. 后记

前言

最近学习react,但网上教程比较混乱,坑很多,而且babel7较之前版本有重大变更。在此开一篇文章记录一下辛酸历程。

1. package.json

列出了各库文件版本。

npm package 名称的变化 (重点)
这是 babel 7 的一个重大变化,把所有 babel-* 重命名为 @babel/*

package.json

{
     
  "name": "react_app",
  "version": "1.0.0",
  "dependencies": {
     
    "@babel/plugin-transform-runtime": "^7.10.3",
    "@babel/preset-react": "^7.10.1",
    "babel-loader": "^8.1.0",
    "babel-preset-mobx": "^2.0.0",
    "cnpm": "^6.1.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "webpack-dev-server": "^3.11.0"
  },
  "devDependencies": {
     
    "@babel/core": "^7.10.3",
    "@babel/polyfill": "^7.10.1",
    "@babel/preset-env": "^7.10.3",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.12"
  },
  "main": "main.js",
  "scripts": {
     
    "start": "webpack-dev-server --hot"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": ""
}


2. webpack.config.js

我的文件结构
webpack4+babel7安装_第1张图片
index.js是babel编译后的文件

index.html


<html lang="cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>webpack4 babel 篇title>
<body>
<div id="root">div>
<script type="text/javascript" src="index.js">script>
body>
html>

App.js

import React from 'react';

class App extends React.Component {
     
    render() {
     
        return (
            <div>
                Hello World!!!<br />
                欢迎来到W3Cschool教程学习!!!
            </div>
        );
    }
}

export default App;

main.js

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

import App from './App.js';

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

webpack.config.js

const path = require('path');

module.exports = {
     
    mode: 'development',
    entry: {
     
        main: './main.js',
    },
    module: {
     
        rules: [
            {
     
                test: /\.js|jsx$/,
                exclude: /node_modules/,
                use: {
     
                    loader: "babel-loader",
                    options:
                        {
     
                            presets:['@babel/preset-react']
                        }
                }
            },
        ],
    },
    devtool: 'source-map',
    // 出口
    output: {
     
        filename: 'index.js',
        path: path.resolve(__dirname, 'dist'),
    },
}

3. .babelrc

这里很重要,直接影响 jsx 编译成功与否
.babelrc

{
     
  "presets": ["@babel/preset-env", "mobx"],
  "plugins": [
    "@babel/plugin-proposal-object-rest-spread",
    "@babel/plugin-transform-runtime"
  ]
}

4. 后记

忙了一天终于跑出来了,也算是有所收获
webpack4+babel7安装_第2张图片

你可能感兴趣的:(web,js,javascript,html5,node.js,reactjs,es6/es7)