美文网首页
【前-react】基于webpack使用create-react

【前-react】基于webpack使用create-react

作者: 一颗语法糖 | 来源:发表于2020-09-25 15:53 被阅读0次

    记录一下坑

    create-react-app

    完成项目初始化

    create-react-app test-antd
    

    然后运行如下命令弹出webpack的配置

    npm run eject
    

    询问时输入y确认,过一会儿会多出一个config目录


    此时运行

    npm run start
    

    报错:


    查看package.json,明明安装了babel-loader。

    报错是因为此时webpack已经分为dev环境和prod环境,所以在package.json里,我们把原来dependencies修改为devDependencies。

    install以后npm run start 一下,看项目能否正常启动


    不出意外,应该就能看到上面的经典logo

    安装antd

    安装相关的依赖

    npm install --save antd 
    npm install --save-dev babel-preset-es2015
    npm install --save-dev babel-plugin-import
    

    然后新建babelrc.的配置文件

    {
      "presets": [
        "es2015",
        "react"
      ],
      "plugins": [
        [
          "import",
          {
            "libraryName": "antd",
            "style": "css"
          }
        ]
      ]
    }
    

    最后运行

    npm run start
    

    就能启动项目

    题外话

    create-react-app默认是用了react-scripts来启动项目,当我们run eject之后,可以发现package.json里的script也发生了明显的变化,在根目录的scripts文件夹里,我们可以看到启动的脚本文件。

    
    // Do this as the first thing so that any code reading it knows the right env.
    process.env.BABEL_ENV = 'development';
    process.env.NODE_ENV = 'development';
    
    // Makes the script crash on unhandled rejections instead of silently
    // ignoring them. In the future, promise rejections that are not handled will
    // terminate the Node.js process with a non-zero exit code.
    process.on('unhandledRejection', err => {
      throw err;
    });
    
    // Ensure environment variables are read.
    require('../config/env');
    
    const fs = require('fs');
    const chalk = require('chalk');
    const webpack = require('webpack');
    const WebpackDevServer = require('webpack-dev-server');
    const clearConsole = require('react-dev-utils/clearConsole');
    const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
    const {
      choosePort,
      createCompiler,
      prepareProxy,
      prepareUrls,
    } = require('react-dev-utils/WebpackDevServerUtils');
    const openBrowser = require('react-dev-utils/openBrowser');
    const paths = require('../config/paths');
    const config = require('../config/webpack.config.dev');
    const createDevServerConfig = require('../config/webpackDevServer.config');
    
    const useYarn = fs.existsSync(paths.yarnLockFile);
    const isInteractive = process.stdout.isTTY;
    
    // Warn and crash if required files are missing
    if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
      process.exit(1);
    }
    
    // Tools like Cloud9 rely on this.
    const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
    const HOST = process.env.HOST || '0.0.0.0';
    
    if (process.env.HOST) {
      console.log(
        chalk.cyan(
          `Attempting to bind to HOST environment variable: ${chalk.yellow(
            chalk.bold(process.env.HOST)
          )}`
        )
      );
      console.log(
        `If this was unintentional, check that you haven't mistakenly set it in your shell.`
      );
      console.log(`Learn more here: ${chalk.yellow('http://bit.ly/2mwWSwH')}`);
      console.log();
    }
    
    // We attempt to use the default port but if it is busy, we offer the user to
    // run on a different port. `choosePort()` Promise resolves to the next free port.
    choosePort(HOST, DEFAULT_PORT)
      .then(port => {
        if (port == null) {
          // We have not found a port.
          return;
        }
        const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
        const appName = require(paths.appPackageJson).name;
        const urls = prepareUrls(protocol, HOST, port);
        // Create a webpack compiler that is configured with custom messages.
        const compiler = createCompiler(webpack, config, appName, urls, useYarn);
        // Load proxy config
        const proxySetting = require(paths.appPackageJson).proxy;
        const proxyConfig = prepareProxy(proxySetting, paths.appPublic);
        // Serve webpack assets generated by the compiler over a web sever.
        const serverConfig = createDevServerConfig(
          proxyConfig,
          urls.lanUrlForConfig
        );
        const devServer = new WebpackDevServer(compiler, serverConfig);
        // Launch WebpackDevServer.
        devServer.listen(port, HOST, err => {
          if (err) {
            return console.log(err);
          }
          if (isInteractive) {
            clearConsole();
          }
          console.log(chalk.cyan('Starting the development server...\n'));
          openBrowser(urls.localUrlForBrowser);
        });
    
        ['SIGINT', 'SIGTERM'].forEach(function(sig) {
          process.on(sig, function() {
            devServer.close();
            process.exit();
          });
        });
      })
      .catch(err => {
        if (err && err.message) {
          console.log(err.message);
        }
        process.exit(1);
      });
    
    

    相关文章

      网友评论

          本文标题:【前-react】基于webpack使用create-react

          本文链接:https://www.haomeiwen.com/subject/xeufuktx.html