ReactJS:导入符号链接组件错误:模块解析失败:意外的标记。您可能需要一个适当的加载器来处理此文件类型。

6

我正在编写一个React组件库,希望在其他项目中使用,而不需要太多的开销(像bit、create-react-library、generact等),也不需要发布到npm。我想使用npm install ../shared_lib将其作为符号链接添加到我的项目的/node_modules中。这个命令会将符号链接添加到项目的node_modules中。在我的shared_lib中,我只有一个测试来export default一个<div></div>

import React from 'react';

const TryTest = function() {
  return (
    <div>
      TryTest
    </div>
  )
}

export default TryTest;

我遇到的问题是将组件导入到正在工作的项目中时出现以下错误:
import TryTest from 'shared_lib';

错误:

ERROR in ../shared_lib/src/index.js 6:4
Module parse failed: Unexpected token (6:4)
You may need an appropriate loader to handle this file type.
| const TryTest = function() {
|   return (
>     <div>
|       TryTest
|     </div>
 @ ./src/App.js 27:0-33 28:12-19
 @ ./src/index.js
 @ multi babel-polyfill ./src/index.js

如果我从shared_lib中导入的不是jsx文件,例如字符串或函数等,那么它可以正常工作。 编辑:应用程序webpack的resolve对象的symlinks属性设置为false。
  resolve: {
    symlinks: false
  },

编辑: 在应用下面的解决方案https://dev59.com/Crroa4cB1Zd3GeqPdRYu#60980492之后,我稍后将符号链接prop更改回true。 我不需要将其设置为false即可使解决方案工作并呈现shared_lib组件。


我的应用程序加载器:

{
  test: /\.jsx?$/,
  include: [
    path.join( __dirname, 'src'), // app/src
    fs.realpathSync(__dirname + '/node_modules/shared_lib'), // app/node_modules/shared_lib/dist/shared_lib.js
  ],
  exclude: /node_modules/,
  use: [ 'babel-loader' ]
}
编辑: 当我按照下面回答中的解决方案进行操作后,加载程序现在看起来像这样:
{
  test: /\.jsx?$/,
  include: [
    path.join( __dirname, 'src'), // app/src
    fs.realpathSync(__dirname + '/node_modules/shared_lib'), // app/node_modules/shared_lib/dist/shared_lib.js
  ],
  exclude: /node_modules/,
  use: [ {
          loader: 'babel-loader',
          options: require("./package.json").babel
          }
        ]
}

应用程序当前的.babelrc设置(我也尝试删除.babelrc,并在package.json中包含相同结果的预设):

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

**编辑:在应用下面答案中的解决方案后,我最终将Babel预设放回了package.json中。
"babel": {
    "presets": [
      "@babel/preset-react",
      "@babel/preset-env"
    ]
},

我花了一段时间寻找解决办法,显然webpack在打包符号链接的react组件时存在问题。我没有使用create-react-app。因此,我尝试在导入到项目之前打包共享库(shared_lib),只是为了看看会发生什么。以下是最终的webpack配置(我也尝试过其他配置):

const pkg = require('./package.json');
const path = require('path');
const buildPath = path.join( __dirname, 'dist' );
const clientPath = path.join( __dirname, 'src');
const depsPath = path.join( __dirname, 'node_modules');
const libraryName = pkg.name;

module.exports = [
  'cheap-module-source-map'
].map( devtool => ({
  bail: true,
  mode: 'development',
  entry: {
    lib : [ 'babel-polyfill', path.join( clientPath, 'index.js' ) ]
  },
  output: {
    path: buildPath,
    filename: 'shared_lib.js',
    libraryTarget: 'umd',
    publicPath: '/dist/',
    library: libraryName,
    umdNamedDefine: true
  },
  // to avoid bundling react
  externals: {
    'react': {
        commonjs: 'react',
        commonjs2: 'react',
        amd: 'React',
        root: 'React'
    }
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        include: [
          clientPath
        ],
        exclude: /node_modules/,
        use: [ 'babel-loader' ],
      },
    ]
  },
  devtool,
  optimization: {
    splitChunks: {
      chunks: 'all',
    },
  }
}));

共享库的package.json文件

{
  "name": "shared_lib",
  "version": "1.0.0",
  "description": "",
  "main": "dist/shared_lib.js",
  "scripts": {
    "clean": "rm -rf dist/",
    "build": "$(npm bin)/webpack --config ./webpack.config.js",
    "prepublish": "npm run clean && npm run build"
  },
  "author": "",
  "license": "ISC",
  "peerDependencies": {
    "react": "^16.8.6"
  },
  "devDependencies": {
    "react": "^16.8.6",
    "@babel/core": "^7.9.0",
    "@babel/preset-env": "^7.9.0",
    "@babel/preset-react": "^7.9.4",
    "babel-loader": "^8.1.0",
    "babel-polyfill": "^6.26.0",
    "webpack": "^4.42.1",
    "webpack-cli": "^3.3.11"
  },
  "babel": {
    "presets": [
      "@babel/preset-react",
      "@babel/preset-env"
    ]
  }
}

包已经成功打包: enter image description here 当我尝试以同样的方式导入组件时: enter image description here 注:保留了HTML标签,未做解释。
import TryTest from 'shared_lib';

输入图像描述

console.log 返回 undefined

输入图像描述

我的应用程序中库文件的路径没问题,因为如果我在 shared_lib/dist/shared_lib.js 中删除所有内容,只写 export default 1,我的 App.js 中的 console.log(TryTest) 将返回 1

我尝试更改 shared_lib/webpack.config 中的 libraryTarget 属性为 libraryTarget: 'commonjs'。然后 console.log(TryTest) 的结果变成了 {shared_lib: undefined}

输入图像描述

有人遇到过这种情况吗?


1
我遇到了这个问题,将 symlinks: false 添加到我的 webpack 配置文件的 resolve 部分解决了它,你试过吗? - Patrick Hund
我尝试在我的应用程序webpack配置中添加symLinks: false。但我仍然收到以下错误: `ERROR in ./node_modules/shared_lib/src/index.js 6:4 Module parse failed: Unexpected token (6:4) You may need an appropriate loader to handle this file type. | const TryTest = function() { | return (
| TryTest | </div>`
- user3006493
1个回答

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接