【问题标题】:Building es6 classes into separate files with webpack使用 webpack 将 es6 类构建到单独的文件中
【发布时间】:2017-04-05 14:52:30
【问题描述】:

我正在尝试为我常用的 React 组件建立一个存储库,然后我可以将其添加到我的项目中,例如 component-kit 并重用它们,所以类似于

import MyComponent from 'component-kit/MyComponent';

目前我有以下项目结构:

component-kit/
   src/
     MyComponent/
       index.js
     index.js
   package.json
   webpack.config.js

index.js 文件通过以下方式导入所有组件:

import('./MyComponent');

然后我使用 webpack 将这些导入中的每一个构建到单独的文件中,这是我的配置,根据可用的代码拆分文档here

const webpack = require('webpack');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'dist.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['env', 'es2015', 'stage-0', 'react'],
            plugins: ['syntax-dynamic-import']
          }
        }
      }
    ]
  }
};

目前,这会输出 2 个文件 dist.js0.dist.js,我无法弄清楚如何以文件输出具有组件名称的方式进行设置,即 MyComponent.js 所以我可以像提到的那样包含它多于。 理想情况下,它们不会将 react 包含在它们的构建中,因为它始终存在于父组件中。

【问题讨论】:

    标签: javascript reactjs webpack code-splitting


    【解决方案1】:

    如果你使用像 JSX 这样基于 babel 的语言,我认为最好使用 babel。
    看看thismaterial-ui npm 脚本。
    我认为 Webpack 通常适合捆绑生产应用程序。
    如果您坚持使用 webpack,您可以使用节点 fs 获取文件名并动态生成类似 This answer 的条目。

    【讨论】:

      猜你喜欢
      • 2017-07-28
      • 2016-12-30
      • 1970-01-01
      • 1970-01-01
      • 2018-12-15
      • 2017-07-25
      • 2018-09-22
      • 1970-01-01
      相关资源
      最近更新 更多