简体   繁体   中英

vite/rollup with @rollup/plugin-babel does not strip template literal backticks when set to ie >= 11

Attempting to use Vite in library mode to compile an ES6 .js files down to a bundled ES5 .js file that will run in Internet Explorer 11. In my actual app there are several files that use ESM import/export, however I have verified that I can reproduce the problem with a single, simplified example file. Which I will include below.

Here is my configuration:

//vite.config.js
const path = require('path');
const { defineConfig } = require('vite');
import { babel } from '@rollup/plugin-babel';

module.exports = defineConfig({
  esbuild: false,
  plugins: [
    babel({
      babelHelpers: 'bundled',
      presets: [['@babel/preset-env', { targets: { browsers: 'defaults, ie >= 11' } }]],
    }),
  ],
  build: {
    outDir: 'javascript',
    lib: {
      entry: path.resolve(__dirname, 'js-src/index.js'),
      name: 'MyLib',
      fileName: (format) => 'my-lib.js',
    },
  },
});

Test File:

const aWord = 'World';
const multiLineString = `
  Hello ${aWord}
`;
console.log(multiLineString);

Resulting output file:

(function(n){typeof define=="function"&&define.amd?define(n):n()})(function(){"use strict";var n=`
  Hello `.concat(aWord,`
`);console.log(n)});

Notice how the transpiled code does down-shift to ES5 (see var instead of const ) but it does not remove the template literal backticks and convert them to some other type of string that is safe for Internet Explorer 11. It only happens on multi-line template literal strings though. A single-line template literal will get changed to a string with " characters.

Looking for a solution to force babel to remove these backtick characters and convert them a supported type of string (that preserves the linebreaks as well)

You can use@vitejs/plugin-legacy to support IE 11 in Vite.

I test with a simple Vite project with vanilla JavaScript and add the test file code like yours. I first run npm i -D @vitejs/plugin-legacy , then use a vite.config.js file like below:

import legacy from '@vitejs/plugin-legacy'

export default {
  plugins: [
    legacy({
      targets: ['ie >= 11'],
      additionalLegacyPolyfills: ['regenerator-runtime/runtime']
    })
  ]
}

Then I run npm run build , the generated js file in dist folder is like below which supports IE 11:

System.register([],(function(){"use strict";return{execute:function(){var e="\n  Hello ".concat("World","\n");console.log(e)}}}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM