【问题标题】:Configure Webpack 4 with aliases, Babel 7 to build React components library使用别名配置 Webpack 4,Babel 7 构建 React 组件库
【发布时间】:2019-03-06 22:22:34
【问题描述】:

我正在尝试创建两个 React 项目:

  • React 组件库(只有没有工作应用程序的组件)

  • 使用已创建组件的 SPA 应用程序(示例应用程序)

我想实现这样的文件夹结构:

  • ./src - 包含 React 组件的目录
  • ./example - 包含使用 ./src 组件的 SPA 应用程序

example 目录中有配置文件(最简单的 React + webpack config 没有 HMR 和其他东西):

webpack.config.js

const HtmlWebPackPlugin = require("html-webpack-plugin");
const aliases = require('./aliases.js');

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      },
      {
        test: /\.html$/,
        use: [
          {
            loader: "html-loader"
          }
        ]
      }
    ]
  },
  resolve: {
    alias: aliases
  },
  plugins: [
    new HtmlWebPackPlugin({
      template: "./src/index.html",
      filename: "./index.html"
    })
  ]
};

aliases.js

var path = require('path');
module.exports = {
  'webpack-alias-react': path.resolve(__dirname, '../src')
};

babel.rc

{
    "presets": ["@babel/preset-env", "@babel/preset-react"]
}

VSCode 别名配置在 jsconfig.json 文件中。

还有我的问题。 当./src/SimpleComponent 包含这样的代码时:

const SimpleComponent = () => {
  return 'string';
};

运行npm run build 命令构建工作应用程序。

但是当./src/SimpleComponent返回时:

const SimpleComponent = () => {
  return <div>abc</div>;
};

npm run buid 命令抛出异常:

../src/SimpleComponent.js 中的错误模块构建失败(来自 ./node_modules/babel-loader/lib/index.js):语法错误: D:\Tranzystor\webpack-alias-react\src\SimpleComponent.js:意外 令牌 (4:9)

如何解决这个 webpack/Babel 配置问题?

为什么&lt;div&gt;可以写成App.js

这是正确的方法吗?

完整代码为here 可用。

【问题讨论】:

    标签: javascript reactjs webpack babeljs


    【解决方案1】:

    我已经解决了 Babel 7 的问题,并且针对此类问题的扩展解决方案是: github

    可以使用webpack 4 + React + Babel 7 + eslint配置了。

    这对 monorepo 解决方案很有帮助。

    将自己的组件库发布到 npm 可以是另一个应用程序。正如我上面提到的./src 目录包含小的反应组件(你想在 npm 上发布的内容)。在./demo 目录中有一个 spa 应用程序,它显示了如何使用提供的组件(例如它可以是故事书)。

    【讨论】:

      猜你喜欢
      • 2019-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-19
      • 2016-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多