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

6 reactjs webpack npm-link

我正在编写一个 React 组件库,我想在其他项目中使用它,而无需太多开销(bit、create-react-library、generact 等)并且无需发布。我想用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;
Run Code Online (Sandbox Code Playgroud)

当我将组件导入我的工作项目时,我面临的问题是以下错误:

import TryTest from 'shared_lib';
Run Code Online (Sandbox Code Playgroud)

错误:

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
Run Code Online (Sandbox Code Playgroud)

如果我从shared_libjsx 文件以外的文件导入任何内容 - 例如,字符串或函数等 - 它工作正常。

编辑:应用程序 webpack 将解析对象的 symlinks 属性设置为 false:

  resolve: {
    symlinks: false
  },
Run Code Online (Sandbox Code Playgroud)

编辑:应用下面答案中的解决方案(/sf/answers/4268634471/)后,我后来将 symlinks 属性更改回 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' ]
}
Run Code Online (Sandbox Code Playgroud)

编辑:当我应用下面答案中的解决方案时,加载器现在看起来像这样:

{
  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
          }
        ]
}
Run Code Online (Sandbox Code Playgroud)

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

{
  "presets": [ "@babel/preset-react", "@babel/preset-env"]
}
Run Code Online (Sandbox Code Playgroud)

**编辑:应用下面答案中的解决方案后,我最终将 babel 预设放回到package.json.

"babel": {
    "presets": [
      "@babel/preset-react",
      "@babel/preset-env"
    ]
},
Run Code Online (Sandbox Code Playgroud)

我研究了一段时间来找到解决方案,显然 webpack 在捆绑符号链接的反应组件时存在问题?我没有使用 create-react-app。 因此,我尝试在将共享库导入到项目之前将其捆绑起来,只是为了看看会发生什么。这是最终的 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',
    },
  }
}));
Run Code Online (Sandbox Code Playgroud)

以及shared_lib 的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"
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

包捆绑无错误: 在此输入图像描述

在此输入图像描述

当我尝试以相同的方式导入组件时:

import TryTest from 'shared_lib';
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

console.log 返回undefined

在此输入图像描述

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

我尝试将 libraryTarget 属性更改shared_lib/webpack.configlibraryTarget: 'commonjs'. 结果console.log(TryTest)变为{shared_lib: undefined}.

在此输入图像描述

有人遇到过这个吗?

小智 2

我找到了最终对我有用的东西,并将符号链接渲染shared_lib到应用程序。

这个答案:https://github.com/webpack/webpack/issues/1643#issuecomment-552767686

shared_lib渲染符号链接组件效果良好。我还没有发现使用此解决方案的任何缺点,但它是迄今为止唯一有效的解决方案。