本文主要是介绍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
我的文件结构
index.js是babel编译后的文件
index.html
<!DOCTYPE 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安装的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!