当前位置: 首页 > 知识库问答 >
问题:

如何配置webpack以从其他lerna包传输文件(从create-react-app弹出)

邓翼
2023-03-14

我正在尝试使用create-react-app包和一个简单的组件库构建一个lerna包。我的组件如下:

import React, { Component } from "react";
import PropTypes from "prop-types";

    class Layout extends Component {
        render = () => {
            let style = {
                fontSize: 14,
                fontFamily:
                    "-apple-system, system-ui, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', sans-serif",
                fontWeight: 400
            };
    
            return <div style={style}>{this.props.children}</div>;
        };
    }
    
    export default Layout;

我最初的create react app如下:

指数js

import React from 'react';
import ReactDOM from 'react-dom';

import App from './components/app/App/App';

ReactDOM.render(<App />, document.getElementById('root'));

一个pp.js

import React, { Component } from "react";

import Layout from "@project/webux/lib/Layout";

class App extends Component {
    render = () => {
        return (
            <Layout>
                Hello!
            </Layout>
        );
    };
}

export default App;

运行时,我遇到以下错误:

../webux/lib/Layout/index.js
SyntaxError: /Volumes/workspace/dev/packages/webux/lib/Layout/index.js: Support for the experimental syntax 'classProperties' isn't currently enabled (5:12):

  3 |
  4 | class Layout extends Component {
> 5 |     render = () => {
    |            ^
  6 |         let style = {
  7 |             fontSize: 14,
  8 |             fontFamily:

Add @babel/plugin-proposal-class-properties (https://git.io/vb4SL) to the 'plugins' section of your Babel config to enable transformation.

发生此错误是因为create-react-app不转译其项目之外的文件。由于我的组件Layout驻留在另一个目录中的另一个lerna包中,因此它不会被转译。

为了解决这个问题,我弹出了我的create react app应用程序,最后得到了以下网页配置文件:,在这里,我添加了====include==一段代码来设置输入目录(我添加了项目上方的目录,因为这将指向我的lerna\packages目录,所以所有包文件都会被处理:

  ...
    resolve: {
      // This allows you to set a fallback for where Webpack should look for modules.
      // We placed these paths second because we want `node_modules` to "win"
      // if there are any conflicts. This matches Node resolution mechanism.
      // https://github.com/facebook/create-react-app/issues/253
      modules: ['node_modules', paths.appNodeModules].concat(
        modules.additionalModulePaths || []
      ),
      // These are the reasonable defaults supported by the Node ecosystem.
      // We also include JSX as a common component filename extension to support
      // some tools, although we do not recommend using it, see:
      // https://github.com/facebook/create-react-app/issues/290
      // `web` extension prefixes have been added for better support
      // for React Native Web.
      extensions: paths.moduleFileExtensions
        .map(ext => `.${ext}`)
        .filter(ext => useTypeScript || !ext.includes('ts')),
      alias: {
        // Support React Native Web
        // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
        'react-native': 'react-native-web',
        // Allows for better profiling with ReactDevTools
        ...(isEnvProductionProfile && {
          'react-dom$': 'react-dom/profiling',
          'scheduler/tracing': 'scheduler/tracing-profiling',
        }),
        ...(modules.webpackAliases || {}),
      },
      plugins: [
        // Adds support for installing with Plug'n'Play, leading to faster installs and adding
        // guards against forgotten dependencies and such.
        PnpWebpackPlugin,
        // Prevents users from importing files from outside of src/ (or node_modules/).
        // This often causes confusion because we only process files within src/ with babel.
        // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
        // please link the files into your node_modules/ and let module-resolution kick in.
        // Make sure your source files are compiled, as they will not be processed in any way.
        new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
      ],
    },
    resolveLoader: {
      plugins: [
        // Also related to Plug'n'Play, but this time it tells Webpack to load its loaders
        // from the current package.
        PnpWebpackPlugin.moduleLoader(module),
      ],
    },
    module: {
      strictExportPresence: true,
      rules: [
        // Disable require.ensure as it's not a standard language feature.
        { parser: { requireEnsure: false } },

        // First, run the linter.
        // It's important to do this before Babel processes the JS.
        {
          test: /\.(js|mjs|jsx|ts|tsx)$/,
          enforce: 'pre',
          use: [
            {
              options: {
                cache: true,
                formatter: require.resolve('react-dev-utils/eslintFormatter'),
                eslintPath: require.resolve('eslint'),
                resolvePluginsRelativeTo: __dirname,
                
              },
              loader: require.resolve('eslint-loader'),
            },
          ],
          //=================== INCLUDED =====================/
          //
          // Included the lenrna packages directory (up directory) 
          // in order to transpile all files from other packages.
          //
          //===================================================
          include: [path.resolve(__dirname, "../.."), paths.appSrc],
        },
        {
          // "oneOf" will traverse all following loaders until one will
          // match the requirements. When no loader matches it will fall
          // back to the "file" loader at the end of the loader list.
          oneOf: [
            // "url" loader works like "file" loader except that it embeds assets
            // smaller than specified limit in bytes as data URLs to avoid requests.
            // A missing `test` is equivalent to a match.
            {
              test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
              loader: require.resolve('url-loader'),
              options: {
                limit: imageInlineSizeLimit,
                name: 'static/media/[name].[hash:8].[ext]',
              },
            },
            // Process application JS with Babel.
            // The preset includes JSX, Flow, TypeScript, and some ESnext features.
            {
              test: /\.(js|mjs|jsx|ts|tsx)$/,
              /// Renato Mendes
              /// This was added to support transpiling of monorepo modules.
              /// See https://github.com/webpack/webpack/issues/6799
              ///
              /// Original:
              /// include: paths.appSrc
              ///
              include: [path.resolve(__dirname, "../.."), path.resolve(paths.lernaRoot + "/packages"), paths.appSrc],
              //              include: paths.appSrc,
              include: [paths.lernaRoot, paths.appSrc],
              loader: require.resolve('babel-loader'),
              options: {
                customize: require.resolve(
                  'babel-preset-react-app/webpack-overrides'
                ),
                
                plugins: [
                  [
                    require.resolve('babel-plugin-named-asset-import'),
                    {
                      loaderMap: {
                        svg: {
                          ReactComponent:
                            '@svgr/webpack?-svgo,+titleProp,+ref![path]',
                        },
                      },
                    },
                  ],
                ],
                // This is a feature of `babel-loader` for webpack (not Babel itself).
                // It enables caching results in ./node_modules/.cache/babel-loader/
                // directory for faster rebuilds.
                cacheDirectory: true,
                // See #6846 for context on why cacheCompression is disabled
                cacheCompression: false,
                compact: isEnvProduction,
              },
            },
            // Process any JS outside of the app with Babel.
            // Unlike the application JS, we only compile the standard ES features.
            {
              test: /\.(js|mjs)$/,
              exclude: /@babel(?:\/|\\{1,2})runtime/,
              loader: require.resolve('babel-loader'),
              options: {
                babelrc: false,
                configFile: false,
                compact: false,
                presets: [
                  [
                    require.resolve('babel-preset-react-app/dependencies'),
                    { helpers: true },
                  ],
                ],
                cacheDirectory: true,
                // See #6846 for context on why cacheCompression is disabled
                cacheCompression: false,
                
                // If an error happens in a package, it's possible to be
                // because it was compiled. Thus, we don't want the browser
                // debugger to show the original code. Instead, the code
                // being evaluated would be much more helpful.
                sourceMaps: false,
              },
            },
            // "postcss" loader applies autoprefixer to our CSS.
            // "css" loader resolves paths in CSS and adds assets as dependencies.
            // "style" loader turns CSS into JS modules that inject <style> tags.
            // In production, we use MiniCSSExtractPlugin to extract that CSS
            // to a file, but in development "style" loader enables hot editing
            // of CSS.
            // By default we support CSS Modules with the extension .module.css
            {
              test: cssRegex,
              exclude: cssModuleRegex,
              use: getStyleLoaders({
                importLoaders: 1,
                sourceMap: isEnvProduction && shouldUseSourceMap,
              }),
              // Don't consider CSS imports dead code even if the
              // containing package claims to have no side effects.
              // Remove this when webpack adds a warning or an error for this.
              // See https://github.com/webpack/webpack/issues/6571
              sideEffects: true,
            },
            // Adds support for CSS Modules (https://github.com/css-modules/css-modules)
            // using the extension .module.css
            {
              test: cssModuleRegex,
              use: getStyleLoaders({
                importLoaders: 1,
                sourceMap: isEnvProduction && shouldUseSourceMap,
                modules: true,
                getLocalIdent: getCSSModuleLocalIdent,
              }),
            },
            // Opt-in support for SASS (using .scss or .sass extensions).
            // By default we support SASS Modules with the
            // extensions .module.scss or .module.sass
            {
              test: sassRegex,
              exclude: sassModuleRegex,
              use: getStyleLoaders(
                {
                  importLoaders: 2,
                  sourceMap: isEnvProduction && shouldUseSourceMap,
                },
                'sass-loader'
              ),
              // Don't consider CSS imports dead code even if the
              // containing package claims to have no side effects.
              // Remove this when webpack adds a warning or an error for this.
              // See https://github.com/webpack/webpack/issues/6571
              sideEffects: true,
            },
            // Adds support for CSS Modules, but using SASS
            // using the extension .module.scss or .module.sass
            {
              test: sassModuleRegex,
              use: getStyleLoaders(
                {
                  importLoaders: 2,
                  sourceMap: isEnvProduction && shouldUseSourceMap,
                  modules: true,
                  getLocalIdent: getCSSModuleLocalIdent,
                },
                'sass-loader'
              ),
            },
            // "file" loader makes sure those assets get served by WebpackDevServer.
            // When you `import` an asset, you get its (virtual) filename.
            // In production, they would get copied to the `build` folder.
            // This loader doesn't use a "test" so it will catch all modules
            // that fall through the other loaders.
            {
              loader: require.resolve('file-loader'),
              // Exclude `js` files to keep "css" loader working as it injects
              // its runtime that would otherwise be processed through "file" loader.
              // Also exclude `html` and `json` extensions so they get processed
              // by webpacks internal loaders.
              exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
              options: {
                name: 'static/media/[name].[hash:8].[ext]',
              },
            },
            // ** STOP ** Are you adding a new loader?
            // Make sure to add the new loader(s) before the "file" loader.
          ],
        },
      ],
    }
    ...

我仍然得到错误,因为我的外部组件没有被传输。

如何使上面的网页包配置传输我的代码,驻留在我的lerna项目的另一个包中?还有其他配置丢失吗?我做错了什么?

共有1个答案

凌华奥
2023-03-14

坏消息是:这是一个常见的问题。自2019年末~3.2.0版本起,Create React应用程序不支持monorepos。如果希望在lerna同级包之间共享组件,许多人要么避免使用“CRApp”,要么在组件库包中包含构建脚本,提交并导出预传输的ES5文件。

消息:我找到了一个似乎有效的修复程序,并且不需要弹出CRA。通过本地构建和测试部署到github页面进行了测试。

它使用了craco,它提供了一个API,可以在不弹出的情况下编辑CRA的网页配置。Craco有插件,可以添加网页包加载程序等;我们需要craco babel装载机:

npm i——保存@craco/craco-craco-babel-loader

...然后还有一些进一步的CRACO设置步骤,请检查https://github.com/gsoft-inc/craco/blob/master/packages/craco/README.md#installation最新消息。在撰写本文时,您需要替换软件包中的以下CRA脚本。json

  • react脚本开始=

然后我们需要在从兄弟包接收ES6 JSX组件的CRA/craco包的根目录中创建一个配置文件,craco.config.js,我们需要列出要发送到babel的包名:

// crago.config.js
// see: https://github.com/sharegate/craco

const path = require('path')
const fs = require('fs')
const cracoBabelLoader = require('craco-babel-loader')

// Handle relative paths to sibling packages
const appDirectory = fs.realpathSync(process.cwd())
const resolvePackage = relativePath => path.resolve(appDirectory, relativePath)

module.exports = {
  plugins: [
    {
      plugin: cracoBabelLoader,
      options: {
        includes: [
          // No "unexpected token" error importing components from these lerna siblings:
          resolvePackage('../some-component-library'),
          resolvePackage('../more-components'),
          resolvePackage('../another-components-package'),
        ],
      },
    },
  ],
}

 类似资料:
  • react-create-app如何与WebPack一起工作?在的默认安装中,webpack配置文件位于何处?在项目文件夹中找不到配置文件。 我没有创建覆盖配置文件。我可以用其他文章管理配置设置,但我想找到常规的配置文件。

  • 问题内容: 我开始通过使用创建一个React应用程序来构建要在NPM上发布(并在其他应用程序中重用)的组件库。不幸的是,默认配置似乎不支持构建此类组件库(请参阅 这些 问题)。所以看来我必须退出。 在弹出后,您是否有一些说明要配置什么,以使其成为可以在其他应用程序中重用的组件库(我猜有些Webpack的东西)? 问题答案: 重新将我的评论变成答案。 不要弹出!CRA将很多东西藏在引擎盖下,弹出会把

  • 问题内容: 我想知道是否可以使用重命名为文件夹之类的其他名称 问题答案: 您可以使用react-app-rewired覆盖反应路径配置。就我而言,我可以更改 config- overrides.js 文件中的路径

  • 我是noob,所以,原谅我,如果这是一个非常基本的问题。我正在创建我的第一个应用程序,它是一个游戏。对于一个文件来说,代码变得太大了(总是上下移动很烦人)。所以我把我的函数放在另一个文件里。问题是addChild不能从其他文件工作。在我的游戏中,当玩家停在一个特定的地方时,必须调用一个节点。如果该函数在“GameScene.swift”文件中,那么它工作得很好,但是如果该函数在任何其他swift文

  • Create React App 不用配置就可以创建 React App。 全局安装: npm install -g create-react-app 创建 App: create-react-app my-appcd my-app/ 启动 npm: npm start 打开 http://localhost:3000/  查看你的 App。 如果你准备将其部署到生产环境,只需创建一个压缩包,并且运行 npm run build。

  • 问题内容: 我有一个包含多个Maven模块的项目 MockIFSClient 访问为 因此 IFSClientTest 运行鳍,因为它们在同一包中。 问题? 尝试访问相同代码的 调用,但现在失败,因为 services / pom.xml 具有以下依赖性 题 我要做出什么改变 这样也可以从不同的模块访问它 问题答案: 这个答案帮助我正确了 如何从Java中的类路径真正读取文本文件 我将代码更改为