webpack使用

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í)行編譯文件的過(guò)程中,會(huì)從項(xiàng)目根目錄下的.babelrc文件中讀取配置。.babelrc是一個(gè)JSON格式的文件。

二、安裝react

npm i -D react react-dom // 安裝react基礎(chǔ)依賴
npm i -D babel-preset-react // 安裝Babel完成語(yǔ)法轉(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" //開(kāi)啟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']
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容