【问题标题】:Can't create a React component in node_modules and use it in an application无法在 node_modules 中创建 React 组件并在应用程序中使用它
【发布时间】:2018-02-13 11:13:39
【问题描述】:

我刚刚使用create-react-app 创建了一个新应用程序。

我创建了一个带有组件的新项目,并使用webpack 将带有babel 的JSX 转换为/dist/bundle.js

我与npm link 链接了我在新项目中创建的应用程序和组件。

在应用程序中我导入了组件,但我总是收到错误

元素类型无效:应为字符串(对于内置组件)或类/函数(对于复合组件),但得到:未定义。您可能忘记从定义组件的文件中导出组件,或者您可能混淆了默认导入和命名导入。

打印应用中的组件都是undefined

这是组件:

index.js

import Root from './Root';

export { Root };

Root.js

import React, { Component } from 'react';
class Root extends Component {
  render() {
    return (<div>{this.props.children}</div>);
  }
}

export default Root;

webpack.config.js

const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          query: {
            presets:['react']
          }
        }
      }
    ]
  }
};

package.json

{
  "name": "my-comp",
  "version": "0.0.1",
  "description": "",
  "main": "dist/bundle.js",
  "dependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react": "^6.24.1",
    "react": "^16.2.0"
  },
  "devDependencies": {
    "webpack": "^3.11.0"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "watch": "webpack --watch",
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

在应用程序中

App.js

import { Root } from 'my-comp';

render() {
    return (
      <Root>
        <span>Hello World</span>
      </Root>
    );
  }

有人知道发生了什么吗?我不能从bundle.js 导入吗?

【问题讨论】:

    标签: reactjs npm webpack babeljs react-component


    【解决方案1】:

    我找到了解决办法。

    webpack.config.js 中,将输出对象更改为:

    output: {
      filename: 'bundle.js',
      path: path.resolve(__dirname, 'dist'),
      libraryTarget: 'commonjs2' //THIS IS IMPORTANT
    }
    

    它告诉引擎这是一个可导出的模块。

    【讨论】:

      猜你喜欢
      • 2020-01-05
      • 2018-01-11
      • 1970-01-01
      • 2021-03-15
      • 1970-01-01
      • 1970-01-01
      • 2019-10-03
      • 2023-04-01
      • 2023-02-08
      相关资源
      最近更新 更多