首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Babel不能在它自己的源代码中解析导入

Babel不能在它自己的源代码中解析导入
EN

Stack Overflow用户
提问于 2021-01-27 23:33:44
回答 1查看 2K关注 0票数 10

我已经将一个React项目升级到了Webpack 5。别名是由Babel解析的。但是当启动Webpack开发服务器时,Babel使构建崩溃,因为它不能解析自己的导入(在其源代码内)。

我已经检查了Babel运行时的节点模块。一切看起来都很棒:

代码语言:javascript
复制
// from the file babel/runtime/helpers/esm/toConsumableArray.js
import arrayWithoutHoles from "./arrayWithoutHoles";
import iterableToArray from "./iterableToArray";
import unsupportedIterableToArray from "./unsupportedIterableToArray";
import nonIterableSpread from "./nonIterableSpread";
export default function _toConsumableArray(arr) {
  return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) 
|| nonIterableSpread();
}

我的终端中显示以下错误:

代码语言:javascript
复制
ERROR in ../../node_modules/@babel/runtime/helpers/esm/toConsumableArray.js 4:0-52
Module not found: Error: Can't resolve './nonIterableSpread' in '/Users/MyNamee/Desktop/MyApp/node_modules/@babel/runtime/helpers/esm'
Did you mean 'nonIterableSpread.js'?
BREAKING CHANGE: The request './nonIterableSpread' failed to resolve only because it was resolved as fully specified
(probably because the origin is a '*.mjs' file or a '*.js' file where the package.json contains '"type": "module"').
The extension in the request is mandatory for it to be fully specified.
Add the extension to the request.
 @ ../../node_modules/rc-slider/es/Range.js 2:0-78 77:43-61 193:23-41 337:23-41
 @ ../../node_modules/rc-slider/es/index.js 2:0-28 6:23-28 10:0-50
 @ ../../kit/src/form/slider/index.tsx
 @ ../../kit/src/form/index.tsx 27:41-71
 @ ../shared/src/panels/card-library/index.tsx 10:15-38
 @ ./src/pages/main.tsx 12:47-93
 @ ./src/app.tsx 11:39-82
 @ ./src/index.tsx 6:38-54

我知道这个问题来自别名解析,因为我在注释别名:{}部分时没有得到这些错误:{}在这个脚本中,别名是由babel别名自动填充的:

代码语言:javascript
复制
const { isArray, size, get, find, reduce } = require("lodash");
const path = require("path");
const BabelConfig = require("../../../babel.config");

const findModuleResolverPlugin = (plugins) => {
  return (
    find(plugins, (plugin) => {
      return isArray(plugin) && plugin[0] === "module-resolver";
    }) || []
  );
};

const getModuleResolverAliasPlugin = (configuration = {}) => {
  const plugin = findModuleResolverPlugin(configuration.plugins);
  if (size(plugin)) {
    return get(plugin[1], "alias", {});
  } else {
    return {};
  }
};

const getBabelAliases = (rootPath = "") => {
  return reduce(
    getModuleResolverAliasPlugin(BabelConfig),
    (aliases, p, alias) => {
      aliases[alias] = path.resolve(rootPath, p);
      return aliases;
    },
    {}
  );
};

module.exports = getBabelAliases;

所以问题似乎是我需要在每个Babel/运行时导入的末尾添加.js。这当然是不切实际的。我应该怎么做才能解决这个问题?

这是我的Babel配置:

代码语言:javascript
复制
module.exports = {
    ignore: ["node_modules"],
      babelrcRoots: ["."],
      presets: [
        "@babel/preset-typescript",
        [
          "@babel/preset-env",
          {
            targets: {
              browsers: ["defaults"],
            },
          },
        ],
        "@babel/preset-react",
      ],
      env: {
        test: {
          plugins: [
            [
              "babel-plugin-react-css-modules",
              {
                generateScopedName: "[local]",
                filetypes: {
                  ".less": {
                    syntax: "postcss-less",
                  },
                },
              },
            ],
            //
          ],
        },
        development: {
          plugins: [
            [
              "babel-plugin-react-css-modules",
              {
                webpackHotModuleReloading: true,
                generateScopedName: "[local]___[hash:base64:5]",
                handleMissingStyleName: "warn",
                filetypes: {
                  ".less": {
                    syntax: "postcss-less",
                  },
                },
              },
            ],
            // "react-hot-loader/babel"
          ],
        },
        production: {
          plugins: [
            [
              "babel-plugin-react-css-modules",
              {
                webpackHotModuleReloading: true,
                generateScopedName: "[hash:base64]",
                filetypes: {
                  ".less": {
                    syntax: "postcss-less",
                  },
                },
              },
            ],
          ],
        },
      },
      plugins: [
        "@babel/plugin-transform-object-assign",
        "@babel/plugin-transform-regenerator",
        "@babel/plugin-transform-runtime",
        "@babel/plugin-syntax-dynamic-import",
        "@babel/plugin-transform-modules-commonjs",
        ["@babel/plugin-proposal-class-properties", { loose: true }],
        [
          "module-resolver",
          {
            cwd: "babelrc",
            root: "./",
            alias: {
              "@components": "./components/src",
              "@pages": "./pages/src",
              "@assets": "./assets",
            },
          },
        ],
      ],
    };

任何帮助都将不胜感激!

EN

回答 1

Stack Overflow用户

发布于 2021-09-20 13:46:43

通过添加以下模块规则,我能够在webpack 4到5升级时解决同样的问题:

代码语言:javascript
复制
// see  https://github.com/webpack/webpack/issues/11467#issuecomment-808618999/
// for details
const webpack5esmInteropRule = {
  test: /\.m?js/,
  resolve: {
    fullySpecified: false
  }
};

config.module.rules = [ webpack5esmInteropRule, ...otherRules ]
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65922329

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档