我正在构建一个npm project(moduleA),并将发布到npm注册表。它使用webpack4babel7的javascript。它本身可以正常工作,但是当我尝试从其他模块测试项目时会遇到一些通天的问题。测试项目使用babel 6.26.3webpack2。当我构建测试项目时,出现以下错误:

ERROR in /Users/dev/moduleA/build/index.js
Module build failed: Error: Requires Babel "^7.0.0-0", but was loaded
 with "6.26.3". If you are sure you have a compatible version of
@babel/core, it is likely that something in your build process is loading
the wrong version. Inspect the stack trace of this error to look for the
first entry that doesn't mention "@babel/core" or "babel-core" to see what
is calling Babel.


上面错误输出中的第一行是关于moduleA包的,该包具有babel7依赖性。我希望来自moduleA的构件不包含有关babel的任何信息。但是看起来moduleA将babel7带到测试项目中,这与测试项目babel6冲突。如何在ModuleA中解决此问题?

以下是moduleA babelrc配置:

{
  "presets": [
    "@babel/preset-env"
  ],
  "plugins": [
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-transform-async-to-generator",
    "@babel/plugin-proposal-object-rest-spread",
    "@babel/plugin-proposal-export-default-from",
    "@babel/plugin-syntax-export-default-from",
    "@babel/plugin-proposal-export-namespace-from"
  ]
}


moduleA中的babel依赖项是:

"devDependencies": {
    "@babel/cli": "^7.2.3",
    "@babel/core": "^7.2.0",
    "@babel/plugin-proposal-class-properties": "^7.2.3",
    "@babel/plugin-proposal-decorators": "^7.2.3",
    "@babel/plugin-proposal-export-default-from": "^7.2.0",
    "@babel/plugin-proposal-export-namespace-from": "^7.2.0",
    "@babel/plugin-proposal-function-sent": "^7.2.0",
    "@babel/plugin-proposal-json-strings": "^7.2.0",
    "@babel/plugin-proposal-numeric-separator": "^7.2.0",
    "@babel/plugin-proposal-object-rest-spread": "^7.2.0",
    "@babel/plugin-proposal-throw-expressions": "^7.2.0",
    "@babel/plugin-syntax-dynamic-import": "^7.2.0",
    "@babel/plugin-syntax-export-default-from": "^7.2.0",
    "@babel/plugin-syntax-import-meta": "^7.2.0",
    "@babel/plugin-transform-arrow-functions": "^7.2.0",
    "@babel/plugin-transform-async-to-generator": "^7.2.0",
    "@babel/plugin-transform-runtime": "^7.2.0",
    "@babel/preset-env": "^7.2.3",
    "@babel/preset-es2015": "^7.0.0-beta.53",
    ...

最佳答案

您可能需要将要运送的文件分为两个:srcdist

src将包含需要Babel和Webpack才能运行的原始代码。

dist是已编译的版本,很可能是无需使用Babel或Webpack即可运行的ES5代码。

请参阅Webpack文档以创建针对生产进行了优化的编译版本:https://webpack.js.org/guides/production

在设法将代码编译好之后,请使用main文件中的package.json属性指向已编译的版本,而不是源(原始)版本。

10-05 19:22