Babel & React
一何之、安裝Babel
npm i -D babel-plugin-transform-runtime // 減少冗余代碼
npm i -D babel-preset-env // 根據(jù)需求選擇不同的Plugins或Presets
npm i -D babel-core babel-loader // webpack接入Babel必須依賴的模塊
Babel執(zhí)行編譯文件的過程中,會(huì)從項(xiàng)目根目錄下的.babelrc文件中讀取配置咽筋。.babelrc是一個(gè)JSON格式的文件溶推。
二、安裝react
npm i -D react react-dom // 安裝react基礎(chǔ)依賴
npm i -D babel-preset-react // 安裝Babel完成語法轉(zhuǎn)換所需的依賴
安裝react依賴后奸攻,修改.babelrc配置文件蒜危,加入React Presets:
{
"presets": [
"react"
]
}
三、入口文件 main.jsx
import * as React from 'react';
import { Component } from 'react';
import { render} from 'react-dom';
class Button extends Component {
render() {
return (<h1>Hello, webpack</h1>)
}
}
render(<Button />, window.document.getElementById('app'));
四睹耐、配置文件 webpack.config.js
const path = require('path');
module.exports = {
entry: './main.jsx',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, './')
},
module: {
rules: [
{
test: /\.jsx?$/,
use: ['babel-loader']
}
]
},
devtool: 'source-map'
}
Typescript & React
一辐赞、安裝typescript
npm i -D typescript awesome-typescript-loader
二、配置文件 tsconfig.json
TypeScript官方提供了能將TypeScript轉(zhuǎn)換成JavaScript的編譯器硝训。我們需要在當(dāng)前項(xiàng)目的根目錄下新建一個(gè)用于配置編譯選項(xiàng)的tsconfig.json文件响委,編譯器默認(rèn)會(huì)讀取和使用這個(gè)文件。
{
"compilerOptions": {
"module": "commonjs", // 編譯出的代碼采用的模塊規(guī)范
"target": "es6", // 編譯出的代碼采用es的哪個(gè)版本
"sourceMap": true,
"importHelpers": true, // 避免代碼冗余
"jsx": "react" //開啟jsx窖梁,支持react
},
"exclude": [
"node_modules"
]
}
三赘风、入口文件 main.tsx(同上)
四、配置文件 webpack.config.js
const path = require('path');
module.exports = {
entry: './main',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, './')
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'awesome-typescript-loader'
}
]
},
devtool: 'source-map',
resolve: {
extensions: ['.tsx', '.ts', '.js']
}
}