如何在构建时使用Babel(而不是Webpack)编译模板字符串

2ic8powd  于 2022-12-08  发布在  Babel
关注(0)|答案(1)|浏览(280)

我正在使用Babel(没有Webpack)来翻译一些ES6代码。代码包含一个模板文字,我想在构建时对其进行评估。
代码包含以下导入,我想在其中注入版本:

  1. const Component = React.lazy(() => import(`projectVersion${__VERSION__}/FooBar`))

我已经使用了许多不同的插件来尝试和实现这一点,如babel-plugin-inline-replace-variablesbabel-plugin-transform-inline-environment-variables,但代码编译成这样:

  1. var Component = /*#__PURE__*/_react.default.lazy(function () {
  2. return Promise.resolve("projectVersion".concat("1", "/FooBar")).then(function (s) {
  3. return _interopRequireWildcard(require(s));
  4. });
  5. });

但我所追求的是沿着这样的东西(就好像我只是手动将版本添加到projectVersion):

  1. const Component = /* #__PURE__*/_react.default.lazy(() => Promise.resolve().then(() => _interopRequireWildcard(require('projectVersion1/FooBar'))))

其中一个原因是,当使用concat运行代码时,我得到错误Critical dependency: the request of a dependency is an expression
提前感谢您的帮助和建议。

详细信息

命令:babel src --out-dir build
巴别塔配置:

  1. module.exports = api => {
  2. api.cache(true)
  3. return {
  4. presets: [
  5. ['@babel/preset-env', {
  6. corejs: 3,
  7. targets: '> 0.25%, not dead',
  8. useBuiltIns: 'usage',
  9. }],
  10. ['@babel/preset-react', {
  11. runtime: 'automatic',
  12. }],
  13. '@babel/preset-typescript',
  14. ],
  15. plugins: [],
  16. }
  17. }
zy1mlcev

zy1mlcev1#

在尝试了许多不同的潜在解决方案后,我最终决定编写一个自定义的Babel插件,用StringLiteral替换TemplateLiteral
下面的代码写得很慢,是针对我的用例的,但希望它能帮助到别人。如果我有时间,我会让它更健壮,更可重用,并在npm上分享。

  1. module.exports = ({ types: t }) => ({
  2. visitor: {
  3. TemplateLiteral(path, state) {
  4. const { version } = state.opts
  5. const { expressions, quasis } = path.node
  6. const expressionStrings = expressions.map(exp => exp.name)
  7. if (expressionStrings.length === 1 && expressionStrings.includes('__VERSION__')) {
  8. const startString = quasis.find(q => q.tail === false).value.raw
  9. const endString = quasis.find(q => q.tail === true).value.raw
  10. path.replaceWith(
  11. t.StringLiteral(`${startString}${version}${endString}`),
  12. )
  13. }
  14. },
  15. },
  16. })

使用插件就像将其添加到Babel插件中一样简单:

  1. plugins: [
  2. ['./babel/interpolate-template-literal', {
  3. version: "99",
  4. }],
  5. ],
展开查看全部

相关问题