webpack+react环境搭建,不必要再使用create-react-app来创建,随意配置更方便

首先是配置文件package.json,里边包括所用到的babel以及关于react的一些依赖包。

{
  "name": "service",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@antv/g6": "^1.2.1",
    "@babel/core": "^7.2.0",
    "@babel/plugin-proposal-class-properties": "^7.2.1",
    "@babel/plugin-proposal-decorators": "^7.2.0",
    "@babel/plugin-proposal-export-default-from": "^7.2.0",
    "@babel/plugin-proposal-export-namespace-from": "^7.2.0",
    "@babel/plugin-proposal-object-rest-spread": "^7.2.0",
    "@babel/plugin-transform-member-expression-literals": "^7.2.0",
    "@babel/plugin-transform-object-assign": "^7.2.0",
    "@babel/plugin-transform-property-literals": "^7.2.0",
    "@babel/plugin-transform-runtime": "^7.2.0",
    "@babel/plugin-transform-spread": "^7.2.0",
    "@babel/plugin-transform-template-literals": "^7.2.0",
    "@babel/preset-env": "^7.2.0",
    "@babel/preset-react": "^7.0.0",
    "@babel/preset-typescript": "^7.1.0",
    "@types/react": "^16.8.22",
    "@types/react-dom": "^16.8.4",
    "antd": "^3.13.6",
    "autoprefixer": "^9.4.2",
    "awesome-typescript-loader": "^5.2.1",
    "axios": "^0.19.0",
    "babel-core": "^7.0.0-0",
    "babel-eslint": "^10.0.2",
    "babel-jest": "^24.0.0",
    "babel-loader": "^8.0.4",
    "babel-plugin-add-module-exports": "^1.0.0",
    "babel-plugin-dynamic-import-webpack": "^1.1.0",
    "babel-plugin-import": "^1.11.0",
    "babel-plugin-inline-import-data-uri": "^1.0.1",
    "babel-polyfill": "^6.26.0",
    "babel-preset-stage-2": "^6.24.1",
    "body-parser": "^1.19.0",
    "classnames": "^2.2.5","core-decorators": "^0.20.0",
    "css-loader": "^2.1.1",
    "echarts": "^3.6.1",
    "eslint-config-airbnb": "^17.1.0",
    "eslint-config-prettier": "^4.2.0",
    "eslint-plugin-babel": "^5.3.0",
    "eslint-plugin-jest": "^22.5.1",
    "eslint-plugin-markdown": "^1.0.0",
    "file-loader": "^3.0.1",
    "fs-extra": "^7.0.1","js-base64": "^2.5.1",
    "js-export-excel": "^1.1.2",
    "jstz": "^2.1.1",
    "jszip": "^3.1.5",
    "moment": "^2.22.2",
    "object-assign": "4.1.1",
    "optimize-css-assets-webpack-plugin": "^5.0.1",
    "pm2": "^3.5.0",
    "promise": "8.0.1",
    "prop-types": "^15.6.0",
    "rc-animate": "^2.4.1",
    "rc-queue-anim": "^1.2.3",
    "react": "^16.8.2",
    "react-dom": "^16.8.2",
    "react-intl": "^2.8.0",
    "react-redux": "^5.0.6",
    "react-router": "^3.0.0",
    "react-router-dom": "^4.0.0",
    "react-router-redux": "^4.0.8",
    "react-table": "^6.8.0",
    "redux": "^3.6.0",
    "redux-thunk": "^2.2.0","sockjs-client": "^1.3.0",
    "ts-loader": "^6.0.4",
    "typescript": "^3.5.2",
    "uglifyjs-webpack-plugin": "^2.1.3",
    "url-loader": "^1.1.2",
    "webstomp-client": "^1.2.5",
    "whatwg-fetch": "2.0.3",
    "xlsx": "^0.11.10",
  },
  "devDependencies": {
    "@babel/preset-es2015": "^7.0.0-beta.53",
    "case-sensitive-paths-webpack-plugin": "2.1.1",
    "chalk": "^2.4.2",
    "clean-webpack-plugin": "0.1.19",
    "copy-to-clipboard": "^3.0.8",
    "copy-webpack-plugin": "^5.0.3",
    "cross-env": "^5.1.6",
    "cryptojs": "^2.5.3",
    "css-modules-require-hook": "^4.2.2",
    "dekko": "^0.2.1",
    "dotenv": "4.0.0",
    "ejs": "^2.6.1",
    "eslint": "^4.4.1",
    "eslint-config-react-app": "^2.0.1",
    "eslint-config-standard": "^12.0.0",
    "eslint-config-standard-react": "^7.0.2",
    "eslint-loader": "1.9.0",
    "eslint-plugin-flowtype": "2.35.0",
    "eslint-plugin-html": "^5.0.3",
    "eslint-plugin-import": "^2.7.0",
    "eslint-plugin-jsx-a11y": "5.1.1",
    "eslint-plugin-node": "^9.1.0",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-react": "^7.1.0",
    "eslint-plugin-standard": "^4.0.0",
    "expose-loader": "^0.7.4",
    "express": "^4.16.4",
    "extract-text-webpack-plugin": "3.0.0",
    "fs": "0.0.1-security",
    "happypack": "^5.0.1",
    "html-res-webpack-plugin": "^4.0.0",
    "html-webpack-plugin": "^3.2.0",
    "http-proxy-middleware": "^0.18.0","jest": "20.0.4",
    "lebab": "^2.7.7",
    "less": "^3.9.0",
    "less-loader": "^5.0.0",
    "less-middleware": "^2.2.1",
    "mini-css-extract-plugin": "^0.6.0",
    "node-less": "^1.0.0",
    "node-notifier": "^5.2.1",
    "nodemailer": "^6.2.1",
    "nodemailer-smtp-transport": "^2.7.4",
    "notifier": "^0.2.0",
    "postcss-flexbugs-fixes": "3.2.0",
    "postcss-loader": "2.0.6",
    "rc-tween-one": "^1.4.5",
    "react-cropper": "^1.0.1",
    "react-dev-utils": "^4.2.3",
    "react-dnd": "^2.6.0",
    "react-dnd-html5-backend": "^2.6.0",
    "react-syntax-highlighter": "^5.7.0",
    "react.proptypes": "^2.0.0",
    "redux-devtools": "^3.4.0",
    "redux-devtools-dock-monitor": "^1.1.2",
    "redux-devtools-log-monitor": "^1.3.0",
    "reqwest": "^2.0.5",
    "reselect": "^3.0.1",
    "style-loader": "0.18.2",
    "sw-precache-webpack-plugin": "0.11.4",
    "webpack": "^4.30.0",
    "webpack-bundle-analyzer": "^3.3.2",
    "webpack-cli": "^3.3.2",
    "webpack-dev-server": "^3.1.14",
    "webpack-manifest-plugin": "1.2.1",
    "webpackbar": "^3.2.0"
  },
  "scripts": {
    "start": "node --max_old_space_size=8096 ./config/start.js","build": "node --max_old_space_size=8096 ./config/prod.js",
    "test": "node --max_old_space_size=8096 ./config/test.js",
    "pro": "node --max_old_space_size=8096 ./config/service.pro.js",
    "production": "node ./config/production.js",
    "development": "node ./config/devPro.js"
  },
  "eslintConfig": {
    "extends": "react-app",
    "env": {
      "browser": true,
      "node": true
    }
  }
}

接下来是开发环境的配置,创建一个config文件夹,创建webpack.config.js

const webpack = require(‘webpack‘);
const path = require(‘path‘);
const HtmlWebpackPlugin = require(‘html-webpack-plugin‘);
const WebpackBar = require(‘webpackbar‘);
const HappyPack = require(‘happypack‘);
const autoprefixer = require(‘autoprefixer‘);
const MiniCssExtractPlugin = require(‘mini-css-extract-plugin‘);
const UglifyJSPlugin = require(‘uglifyjs-webpack-plugin‘);
const os = require(‘os‘);
const happyThreadPool = HappyPack.ThreadPool({ size: os.cpus().length });
module.exports = {
    output: {
        filename: ‘static/js/[name].[hash]‘ + new Date().getTime() + ‘.js‘,
        path: path.resolve(__dirname, ‘../public‘),
        chunkFilename: ‘static/js/[name].[hash].bundle.js‘,
        publicPath: ‘/‘
    },
    module: {
        rules: [
            {
                test: /\.js?$/,
                exclude: [path.resolve(__dirname, ‘node_modules‘)],
                loader: ‘happypack/loader?id=js_babel‘
            },
            {
                test: /\.tsx?$/,
                use: {
                    loader: ‘ts-loader‘,
                }
            },
            {
                test: /\.css$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    {
                        loader: ‘css-loader‘,
                        options: {
                            sourceMap: true,
                        },
                    },
                    {
                        loader: ‘postcss-loader‘,
                        options: Object.assign({}, autoprefixer({ overrideBrowserslist: [‘last 2 versions‘, ‘Firefox ESR‘, ‘> 1%‘, ‘ie >= 9‘] }), { sourceMap: true }),
                    },
                ],
            },
            {
                test: /\.less$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    {
                        loader: ‘css-loader‘,
                        options: {
                            sourceMap: true,
                        },
                    },
                    {
                        loader: ‘postcss-loader‘,
                        options: Object.assign({}, autoprefixer({ overrideBrowserslist: [‘last 2 versions‘, ‘Firefox ESR‘, ‘> 1%‘, ‘ie >= 9‘] }), { sourceMap: true }),
                    },
                    {
                        loader: ‘less-loader‘,
                        options: {
                            javascriptEnabled: true,
                            sourceMap: true,
                        },
                    },
                ],
            },
            {
                test: /\.(gif|jpg|png|woff|svg|eot|ttf)\??.*$/,
                loader: ‘url-loader?limit=8192&name=images/[hash:8].[name].[ext]‘
            }
        ],
    },
    externals: {
        react: ‘React‘,
        ‘react-dom‘: ‘ReactDOM‘,
        jquery: ‘jQuery‘
    },
    optimization: {
        splitChunks: {
            chunks: ‘async‘,
            minSize: 30000,
            maxSize: 0,
            minChunks: 1,
            maxAsyncRequests: 5,
            maxInitialRequests: 3,
            automaticNameDelimiter: ‘~‘,
            name: true,
            cacheGroups: {
                vendors: {
                    test: /[\\/]node_modules[\\/]/,
                    priority: -10
                },
                default: {
                    minChunks: 2,
                    priority: -20,
                    reuseExistingChunk: true
                }
            }
        }
    },
    resolve: {
        extensions: [‘.js‘, ‘.json‘, ‘.jsx‘, ‘.ts‘, ‘.tsx‘],
        alias: {
            UTIL_: path.resolve(__dirname, ‘../src/util.js‘),
            common_: path.resolve(__dirname, ‘..src/components/modelCommon/common.js‘),
            modelCommon: path.resolve(__dirname, ‘..src/components/modelCommon‘),
        }
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: "static/css/index.[hash].css"
        }),new HappyPack({
            id: ‘js_babel‘,
            threadPool: happyThreadPool,
            loaders: [
                {
                    loader: ‘babel-loader‘,
                    options: {
                        presets: [
                            "@babel/preset-env",
                            "@babel/preset-react",
                        ]
                    }
                },
                {
                    loader: ‘eslint-loader‘
                }
            ],
            verbose: true
        }),
        new HtmlWebpackPlugin({
            inject: ‘body‘,
            template: path.resolve(__dirname, ‘../public/index.1.html‘)
        })
    ]
}

创建start.js

process.env.NODE_ENV = ‘development‘;
process.env.BABEL_ENV = ‘development‘;

const util = require(‘./util‘)
const config = require(‘./webpack.config.config.js‘)
const { startApp } = util;

startApp({
    proxy: ‘http://www.xx.com‘,
    config,
    mode:‘development‘,
    port:3000,
})

startApp方法

function startApp({ proxy, config,mode ,port}) {
    const inoutName = ‘main‘;
    config.devtool = ‘cheap-module-eval-source-map‘;
    config.entry = {
        [inoutName]: path.resolve(__dirname, ‘../src/index.js‘),
        webpackHotDevClient: require.resolve(‘react-dev-utils/webpackHotDevClient‘)
    };
    config.mode = mode;
    config.plugins.push(new webpack.NamedModulesPlugin());
    config.plugins.push(new webpack.HotModuleReplacementPlugin());
    const webpackConfig = webpack(config);
    const devServer = new WebpackDevServer(webpackConfig, {
        contentBase: path.resolve(__dirname, ‘../public‘),
        compress: true,
        stats: {
            warnings: true,
            errors: true,
            children: false
        },
        historyApiFallback: true,
        clientLogLevel: ‘none‘,
        proxy: {
            ‘/userModel‘: {
                target:proxy,
                changeOrigin: true,
                secure: false,
            },
            ‘/‘: {
                target: proxy,
                changeOrigin: true,
                bypass: function (req) {
                    if (/\.(gif|jpg|png|woff|svg|eot|ttf|js|jsx|json|css|pdf)$/.test(req.url)) {
                        return req.url;
                    }
                    //return req.url;
                }
            }
        }
    });

    devServer.listen(port, process.env.HOST || ‘0.0.0.0‘, (err) => {
        if (err) {
            return console.log(err);
        }
        clearConsole();
        console.log(chalk.rgb(212, 133, 184)(‘?? 启动成功:‘), chalk.bgGreen(‘http://‘ + host() +‘:‘+ port), ‘\n‘);
        openBrowser(‘http://‘ + host() +‘:‘+ port)
    });
}

开发环境基本上搭建完成。开始搭建生产环境

process.env.NODE_ENV = ‘production‘;
process.env.BABEL_ENV = ‘production‘;

const webpack = require(‘webpack‘);
const path = require(‘path‘);
const fs = require(‘fs‘);
const fss = require(‘fs-extra‘);
const webpackConfig = require(‘./webpack.config.config.js‘);
const chalk = require(‘chalk‘);
const notifier = require(‘node-notifier‘);
const OptimizeCSSAssetsPlugin = require(‘optimize-css-assets-webpack-plugin‘);
const inoutName = ‘main‘;
const inputJs = path.resolve(__dirname, ‘../src/index.js‘);
const clearConsole = require(‘react-dev-utils/clearConsole‘);
createFolder();
clearConsole();
webpackConfig.devtool = false;
webpackConfig.entry = {
    [`${inoutName}`]: inputJs
}
webpackConfig.mode = ‘production‘;
webpackConfig.plugins.push(new webpack.optimize.ModuleConcatenationPlugin());
webpackConfig.plugins.push(new webpack.LoaderOptionsPlugin({
    minimize: true,
}));

fss.emptyDirSync(path.resolve(__dirname, ‘../build‘))
fss.emptyDirSync(path.resolve(__dirname, ‘../public/static‘))

webpack(webpackConfig).run((err, options) => {
    clearConsole();
    if (err) {
        console.error(‘? 错误信息:‘, err);
        return;
    }
    if (err || options.hasErrors()) {
        if (options.compilation.warnings) {
            options.compilation.warnings.forEach(item => {
                console.log(chalk.green(‘?? 警告:‘, item.message, ‘‘)), ‘\n‘);
            })
        }

        console.log(chalk.yellow(options.compilation.errors[0].error.message), ‘\n‘);
        console.log(chalk.red(‘? 错误信息:‘, options.compilation.errors));
        return;
    }
    notice(‘ServiceBot: 打包成功!‘)
    const { startTime, endTime } = options;
    const times = (endTime - startTime) / 1e3 / 60;
    if (options.compilation.warnings) {
        options.compilation.warnings.forEach(item => {
            console.log(chalk.green(‘?? 警告:‘, item.message)), ‘\n‘);
        })
    }
    console.log(chalk.yellow(‘        -                                         ‘));
    console.log(chalk.yellow(‘       | |                           _          _ ‘));
    console.log(chalk.yellow(‘       | |                          | |        (_)‘));
    console.log(chalk.yellow(‘ _____ | |__   _____   ____    ____ | |  _____  _ ‘));
    console.log(chalk.yellow(‘(___  )|  _  | (____| |  _  | / _  || | | ___ || |‘));
    console.log(chalk.yellow(‘ / __/ | | | |/ ___ | | | | |( (_| || | | ____|| |‘));
    console.log(chalk.yellow(‘(_____)|_| |_||_____| |_| |_| |___ ||_) |_____)|_|‘));
    console.log(chalk.yellow(‘                             (_____|              ‘), ‘\n‘);
    console.log(chalk.rgb(212, 133, 184)(‘?? 开始时间:‘), chalk.bgGreen(isCurrentTime(new Date(startTime))), ‘\n‘);
    console.log(chalk.rgb(212, 133, 184)(‘?? 结束时间:‘), chalk.bgGreen(isCurrentTime(new Date(endTime))), ‘\n‘);
    console.log(chalk.rgb(212, 133, 184)(‘? 总共用时:‘), chalk.yellowBright(`${parseFloat(times).toFixed(2)}分钟`), ‘\n‘);
    copyFolder(path.resolve(__dirname, ‘../public‘), path.resolve(__dirname, ‘../build‘));
    fss.emptyDirSync(path.resolve(__dirname, ‘../public/static‘))
})

function notice(message) {
    notifier.notify({
        title: ‘ServiceBot‘,
        message,
        icon: path.join(__dirname, ‘../public/img/8.jpg‘),
        sound: true,
        wait: true
    });
}

notifier.on(‘click‘, function (notifierObject, options) {
    // Triggers if `wait: true` and user clicks notification
});

notifier.on(‘timeout‘, function (notifierObject, options) {
    notice()
});

function copyFolder(src, tar) {
    fs.readdirSync(src).forEach(path => {
        const newSrc = `${src}/${path}`;
        const newTar = `${tar}/${path}`
        const st = fs.statSync(newSrc);
        if (st.isDirectory()) {
            fs.mkdirSync(newTar)
            return copyFolder(newSrc, newTar)
        }
        if (st.isFile()) {
            fs.writeFileSync(newTar, fs.readFileSync(newSrc))
        }
    })
}

function createFolder() {
    if (!fs.existsSync(path.resolve(__dirname, ‘../build‘))) {
        fs.mkdirSync(path.resolve(__dirname, ‘../build‘))
    }
}

function isCurrentTime(time) {
    const y = time.getFullYear();
    const month = time.getMonth() + 1;
    const hour = time.getHours();
    const min = time.getMinutes();
    const sec = time.getSeconds();
    const day = time.getDate();
    const m = month < 10 ? `0${month}` : month;
    const h = hour < 10 ? `0${hour}` : hour;
    const mins = min < 10 ? `0${min}` : min;
    const s = sec < 10 ? `0${sec}` : sec;
    const d = day < 10 ? `0${day}` : day;
    return `${y}-${m}-${d} ${h}:${mins}:${s}`
}

生产环境基本搭建完成,如果想直接启动本地生产项目,可以使用express代理一个生产环境

最后需要在public目录下增加html页面

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="Access-Control-Allow-Origin" content="*">
  <link rel="shortcut icon" href="favicon.ico">

  <title>Service</title>
  <style>
    .loader {
      position: absolute;
      top: 50%;
      left: 40%;
      margin-left: 10%;
      transform: translate3d(-50%, -50%, 0);
      font-size: 40px;
      font-weight: bold;
    }

    .loader span {
      animation: slide 1s infinite;
      color: #ccc;
    }

    .loader span:nth-child(1) {
      animation-delay: .1s
    }

    .loader span:nth-child(2) {
      animation-delay: .2s
    }

    .loader span:nth-child(3) {
      animation-delay: .3s
    }

    .loader span:nth-child(4) {
      animation-delay: .4s
    }

    .loader span:nth-child(5) {
      animation-delay: .5s
    }

    @-webkit-keyframes slide {
      0% {
        color: #ccc
      }

      50% {
        opacity: .3;
        color: #666
      }
    }

    @keyframes slide {
      0% {
        color: #ccc
      }

      50% {
        opacity: .3;
        color: #666
      }
    }
  </style>
</head>

<body id="body">
  <div id="root">
    <div class="loader">
      <span>S</span>
      <span>e</span>
      <span>r</span>
      <span>v</span>
      <span>i</span>
      <span>c</span>
      <span>e</span>
    </div>
  </div>
  <script src="/data/react.production.min.js"></script>
  <script src="/data/react-dom.production.min.js"></script>
</body>

</html>

基本结构搭建完成,现在是处理index.js入口文件。

会用到react-redux 做了初步的国际化方案

import * as React from ‘react‘;
import * as ReactDOM from ‘react-dom‘;
import { Provider } from ‘react-redux‘
import { createStore } from ‘redux‘
import Routers from ‘./routerMenu/preRouter‘;
import Reducers from ‘./routerMenu/rootReducers‘;
import enhancer from ‘./routerMenu/configureStore‘
import { IntlProvider, addLocaleData } from ‘react-intl‘;
import { isEnUS } from ‘./util‘
import { LocaleProvider } from ‘antd‘;
import zh_CN from ‘antd/lib/locale-provider/zh_CN‘;
import en_US from ‘antd/lib/locale-provider/en_US‘;
import ‘moment/locale/zh-cn‘;
import ‘babel-polyfill‘;
import ‘whatwg-fetch‘;
import zhCN from ‘./zh-CN‘;
import enUS from ‘./en-US‘;

let store = createStore(Reducers, {}, enhancer);
const { useState, useEffect } = React;
const { location, localStorage, addEventListener } = window;
function App({ onChange }) {
    const appLocale = isEnUS(location.hash) ? enUS : zhCN
    addLocaleData(appLocale.data);
    const [AL, setLocale] = useState(appLocale);
    const [key, setKey] = useState(0);
    const callback = (e) => {
        localStorage.setItem(‘locale‘, e);
        const hash = window.location.hash;
        setLocale(isEnUS(location.hash) ? enUS : zhCN)
        setKey(Math.random() * 1 + 100)
    }

    useEffect(() => {
        addEventListener(‘hashchange‘, (ev) => {
            const old = ev.oldURL;
            const newUrl = ev.newURL;
            const oAddr = ev.oldURL.replace(/^.+(?=\/\/)/, ‘‘);
            const nAddr = ev.newURL.replace(/^.+(?=\/\/)/, ‘‘);

            if (
                oAddr !== nAddr &&
                (nAddr.indexOf(‘-en‘) >= 0 || oAddr.indexOf(‘-en‘) >= 0) &&
                !((nAddr.indexOf(‘-en‘) >= 0) && oAddr.indexOf(‘-en‘) >= 0)
            ) {
                setLocale(isEnUS(location.hash) ? enUS : zhCN)
                setKey(Math.random() * 1 + 100)
            }

            const urlArray = [

            ]
            const isClear = urlArray.some(key =>{
                return (old.indexOf(key) >= 0 && !(newUrl.indexOf(key) >= 0))
            })

            if(isClear){
                window.sessionStorage.clear();
            }
        })
        return () => {
            removeEventListener(‘hashchange‘, () => { })
        };
    }, [location.hash])
    return (
        <IntlProvider key={key} locale={AL.locale} messages={AL.messages}>
            <Provider store={store}>
                <LocaleProvider locale={AL.locale === ‘zh-CN‘ ? zh_CN : en_US}>
                    <div>hello</div>
                </LocaleProvider>
            </Provider>
        </IntlProvider>
    )
}

const RenderApp = () => {
    const [key, setKey] = useState(0);
    function onChange(key) {
        setKey(Math.random() * 1 + 1)
    }
    return (<App onChange={onChange} key={key} />)
}

ReactDOM.render(
    <RenderApp />,
    document.getElementById(‘root‘)
);

运行npm start  就可以看见 hello了 其他的路由还需要自己配置,简单方便,需要配置需要配置eslint的还需要单独夹一个文件。

原文地址:https://www.cnblogs.com/leijuan/p/11347971.html

时间: 2024-10-07 11:43:33

webpack+react环境搭建,不必要再使用create-react-app来创建,随意配置更方便的相关文章

webpack+babel+ES6+react环境搭建

webpack+babel+ES6+react环境搭建 步骤: 1 创建项目结构 注意: 先创建一个项目目录  react  这个名字自定义,然后进入到这个目录下面 mkdir app //创建app目录 用来存放项目源文件 mkdir dist // 创建dist目录 用来存放打包好的文件 touch .gitignore //创建.gitignore 用来添加git 忽略的文件 touch webpack.config.js //创建webpack的配置文件 cd app //进入到app目

React+Webpack+ES6环境搭建(自定义框架)

引言 目前React前端框架是今年最火的.而基于React的React Native也迅速发展.React有其独特的组件化功能与JSX的新语法,帮助前端设计有了更好的设计与便捷,而React Native更是扩大了前端的边界. 说道React,那就不得不说一下Webpack凭借它异步加载和可分离打包等优秀的特性,走在取代Grunt和Gulp的路上.而面向未来的ES6,更是支持模块化处理. 下面我就分享一下关于Webpack+React+ES6的环境搭建(通用)[附加发布版] 准备工作 首先需要准

最小白的webpack+react环境搭建

本文也同步发表在我的公众号"我的天空" 从零开始,用最少的配置.最少的代码.最少的依赖来搭建一个最简单的webpack+react环境. 最近在玩webpack+react+移动端,那么第一步自然是搭建相关的环境,本来网上的教程很不错,只是前端相关的东西发展太过迅猛,只相隔了半年有些东西的版本就不对了,有些配置.命令等照着之前的教程做就可能会掉到坑里去,别问我怎么知道的,我刚刚从坑里爬出来,因此赶紧写篇文章来记录一下,也算是让自己再巩固一下. 本篇完全是从零开始,用最少的配置.最少的代

React学习笔记-1-什么是react,react环境搭建以及第一个react实例

什么是react?react的官方网站:https://facebook.github.io/react/下图这个就是就是react的标志,非常巧合的是他和我们的github的编辑器Atom非常相似.react是Facebook官方推出的一个javascript的库,现在已经有了非常多的库和框架Facebook为什么还要开发一款新的框架呢?原因就是 Facebook遇到了一些新的问题.Facebook需要解决的问题是构建数据不断变化的大型应用.大型应用是什么意思?数据不断变化带来什么问题呢? 

window10下vue-cli及webpack的环境搭建

1.首先确保nodejs安装,可使用node -v验证nodejs版本                        //nodejs内嵌npm 2.win+x进入cmd的管理员权限,运行cnpm install -g vue-cli              //管理员权限下安装vue-cli 3.vue  init webpack demo                                                        //进入自己设置的项目目录,新建自己的de

vue+webpack工程环境搭建

使用Vue-cli脚手架(属于vue全家桶)快速构建一个项目: [1]首先需要安装好node.js; [2]安装webpack,指令$npm install -g webpack; //如果之前有安装可以用$webpack -v查看当前webpack版本: [3]安装Vue-cli,指令$npm install -g vue-cli; [4]$Vue init webpack projectName ;//生成项目名称 [5]$cd projectName;  //进入工程目录 [6]$npm

react环境搭建

react.js有类似于vue-cli的脚手架 ---- create-react-app 以下是采用了淘宝国内镜像资源去下载的react脚手架图 安装完脚手架后,还必须初始化react应用在cmd键入: create-react-app my-app 到这里,react的脚手架工作已经准备完毕,使用npm start启动react应用 react脚手架启动项目完毕 原文地址:https://www.cnblogs.com/xiyangcai/p/8463545.html

React环境搭建(非脚手架)

逆战班 一.建立一个项目的目录 在目录命令行中 npm init -y会在目录中产生一个文件package.json 二.安装React,react.development.js npm i react --save (或yarn add react) 会在目录中有一个node_modules目录, 找到react目录, 找到这个目录下的umd目录,拷贝umd目录下react.development.js到自己的js目录下 三.react-dom.development.js npm i rea

vue+webpack项目环境搭建

首先安装node.js 下载地址:https://nodejs.org/en/download/ 看下是否成功安装 node -v 原文地址:https://www.cnblogs.com/adbg/p/9627781.html