【问题标题】:Babel does not transpile imported modules from 'node_modules'Babel 不会从 'node_modules' 转译导入的模块
【发布时间】:2018-07-11 15:28:41
【问题描述】:

我从 node_modules 转译导入的模块时遇到问题。 Babel 出于某种原因不会转译从 node_modules 导入的模块,而是转译从 src 导入的模块。

这里是一个示例 repo:https://github.com/NikitaKA/babeltest

ma​​in.js

// result code contains const and let, but it shouldn't. :(

index.js

import qs from 'query-string; // not transpiled
import lib from './lib' // transpiled

const query = qs.parse(window.location.search);

webpack.config.js

const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'main.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  }
};

.babelrc

{
  "presets": [
    ["@babel/preset-env", {
      "modules": false,
      "targets": {
        "chrome": 39
      }
    }],
    ["@babel/preset-stage-1", {
      "modules": false,
      "decoratorsLegacy": true,
      "pipelineProposal": "minimal"
    }]
  ],
  "plugins": [
    "transform-es2015-constants",
    "@babel/plugin-transform-block-scoping",
    "@babel/plugin-transform-runtime"
  ]
}

【问题讨论】:

  • 这通常是应该的。您是否有特殊原因要转译位于 node_modules 中的已经可以分发的模块?
  • 顺便说一下,示例 repo 缺少 webpack-cli/webpack-command,因此 start 命令在 OOTB 中不起作用。
  • 哎呀,好像我已经全局安装了webpack-cli。
  • @AKX node_modules中的lib使用const,我想编译成var支持下层浏览器

标签: javascript webpack babeljs


【解决方案1】:

这种情况下的解决方案是再次编译模块,这可以通过修改 webpack 配置中的 exclude 属性来完成:

{
  test: /\.js$/,
  exclude: /node_modules\/(?!(es6-module|another-es6-module)\/).*/,
},

模块 es6-moduleanother-es6-module 将不再被 webpack 忽略,并将与您的其余源代码一起转译。

请参阅GitHub issue on the webpack project

使用webpack@3.12.0babel-core@6.26.3babel-core@6.26.3 测试

【讨论】:

    【解决方案2】:

    扩展我的 cmets:

    你真的不想转译所有的node_modules——这需要很长时间,而且大部分代码应该已经是 ES5(除非它们实际上是 ES6 模块,在这种情况下是 ES6 条目点在package.json 清单中被宣布为"module"

    query-string@6.x不是,它在its README中这么说:

    此模块面向 Node.js 6 或更高版本以及最新版本的 Chrome、Firefox 和 Safari。如果您想支持旧版浏览器,请使用版本 5:npm install query-string@5

    【讨论】:

    • 我明白你的意思。你说得对,我不应该编译分布式模块,特别是如果有支持旧浏览器的旧版本的版本(我没有检查,我的错)。但是我觉得很奇怪,你不能将现代库编译成 ES5,如果没有旧版本怎么办?在我的情况下,有必要在旧浏览器下编译项目,这很幸运,它只是项目中的一个外部库,并且具有 ES5 模拟:)。
    • 无论如何,有没有办法从node_modules转译模块?
    • 来自webpack issue 2031: { test: /\.js$/, exclude: /node_modules\/(?!(MY-MODULE|ANOTHER-ONE)\/).*/, },
    • 据我了解,OP 想要 转换 node_modules (或至少特定的不符合标准的模块)。您提到了自己的模块should already be ES5(关键字should)。所以有时模块没有正确打包,我们可能需要手动转换它们......你的答案没有回答那个问题
    【解决方案3】:

    如果您使用的是 Vue,有一个简单的解决方案。只需在transpileDependencies 中列出您的模块:

    vue.config.js

    module.exports = {
       publicPath: '',
       outputDir: 'www',
       transpileDependencies: [
        'query-string'
      ],
    }
    

    【讨论】:

    • 超级好!这也适用于使用 lerna 添加的软件包
    猜你喜欢
    • 2015-10-27
    • 2019-08-25
    • 2019-01-19
    • 2019-04-14
    • 2019-09-30
    • 2019-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多