Giter Site home page Giter Site logo

rollup-plugin-esbuild's Introduction

💛 You can help the author become a full-time open-source maintainer by sponsoring him on GitHub.


rollup-plugin-esbuild

npm version npm downloads

esbuild is by far one of the fastest TS/ESNext to ES6 compilers and minifier, this plugin replaces rollup-plugin-typescript2, @rollup/plugin-typescript and rollup-plugin-terser for you.

Install

yarn add esbuild rollup-plugin-esbuild --dev

Usage

In rollup.config.js:

import esbuild from 'rollup-plugin-esbuild'

export default {
  plugins: [
    esbuild({
      // All options are optional
      include: /\.[jt]sx?$/, // default, inferred from `loaders` option
      exclude: /node_modules/, // default
      sourceMap: true, // default
      minify: process.env.NODE_ENV === 'production',
      target: 'es2017', // default, or 'es20XX', 'esnext'
      jsx: 'transform', // default, or 'preserve'
      jsxFactory: 'React.createElement',
      jsxFragment: 'React.Fragment',
      // Like @rollup/plugin-replace
      define: {
        __VERSION__: '"x.y.z"',
      },
      tsconfig: 'tsconfig.json', // default
      // Add extra loaders
      loaders: {
        // Add .json files support
        // require @rollup/plugin-commonjs
        '.json': 'json',
        // Enable JSX in .js files too
        '.js': 'jsx',
      },
    }),
  ],
}
  • include and exclude can be String | RegExp | Array[...String|RegExp], when supplied it will override default values.
  • It uses jsx, jsxDev, jsxFactory, jsxFragmentFactory and target options from your tsconfig.json as default values.

Declaration File

There are serveral ways to generate declaration file:

  • Use tsc with emitDeclarationOnly, the slowest way but you get type checking, it doesn't bundle the .d.ts files.
  • Use rollup-plugin-dts which generates and bundle .d.ts, also does type checking.
  • Use api-extractor by Microsoft, looks quite complex to me so I didn't try it, PR welcome to update this section.

Use with Vue JSX

Use this with rollup-plugin-vue-jsx:

import vueJsx from 'rollup-plugin-vue-jsx-compat'
import esbuild from 'rollup-plugin-esbuild'

export default {
  // ...
  plugins: [
    vueJsx(),
    esbuild({
      jsxFactory: 'vueJsxCompat',
    }),
  ],
}

Standalone Minify Plugin

If you only want to use this plugin to minify your bundle:

import { minify } from 'rollup-plugin-esbuild'

export default {
  plugins: [minify()],
}

Optimizing Deps

You can use this plugin to pre-bundle dependencies using esbuild and inline them in the Rollup-generated bundle:

esbuild({
  optimizeDeps: {
    include: ['vue', 'vue-router'],
  },
})

This eliminates the need of @rollup/plugin-node-modules and @rollup/plugin-commonjs.

Note that this is an experimental features, breaking changes might happen across minor version bump.

TODO: Maybe we can scan Rollup input files to get a list of deps to optimize automatically.

Sponsors

sponsors

License

MIT © EGOIST (Kevin Titor)

rollup-plugin-esbuild's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rollup-plugin-esbuild's Issues

tsconfig.json support?

Hi there!

Thanks for the helpful plugin!
I'm trying to integrate esbuild into rollup using your plugin and it seems that it doesn't support tsconfig.json completely?
At least it doesn't respect compilerOptions.baseUrl and compilerOptions.paths.
These are path aliases which allow to write

import '@alias/module'

instead of

import `../../../../../../../../some-folder/module`

(well, I think you know, but just for clarity :) )
And as far as I know esbuild itself supports these options (evanw/esbuild#60 and evanw/esbuild#38 (comment)).

Or maybe I missed something?

legalComments option doesn't apply to libraries in node_modules

I have set legalComments to none, it can only trim the legal comments in current project, but the legal comments of library in node_modules are still in the result bundle.

My config is something like:

import alias from '@rollup/plugin-alias';
import commonjs from '@rollup/plugin-commonjs';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import scss from 'rollup-plugin-scss';
import esbuild from 'rollup-plugin-esbuild';
import vue from 'rollup-plugin-vue';

// `npm run build` -> `production` is true
// `npm run dev` -> `production` is false
const production = !process.env.ROLLUP_WATCH;

/** @type { import('rollup').RollupOptions } */
export default {
  input: [
    './src/main.ts'
  ],
  output: {
    dir: 'dist',
    chunkFileNames: production ? "chunks/[name]-[hash].js" : "chunks/[name].js",
    format: 'es',
    sourcemap: !production
  },
  watch: { clearScreen: false },
  treeshake: production,
  external: [],
  plugins: [
    vue({}),
    esbuild({ tsconfig: 'tsconfig.json', sourceMap: !production, minify: production, legalComments: 'none' }),
    scss({
      output: 'dist/main.css', sass: require('sass'), sourceMap: !production,
      outputStyle: !production ? 'expanded' : 'compressed'
    }),
    alias({}),
    nodeResolve({}),
    commonjs({})
  ],
  preserveEntrySignatures: false
}

Any idea?

sourceMaps option is always false while making call to getRenderChunk

In following code the sourceMap option passed to getRenderChunk function will always be false:

  let sourceMap = false
  return {
    name: 'esbuild-minify',

    outputOptions({ sourcemap }) {
      sourceMap = options.sourceMap ?? !!sourcemap
      return null
    },

    renderChunk: getRenderChunk({
      minify: true,
      ...options,
      sourceMap,
    }),
  }
} 

Changing the order of properties would fix the issue

renderChunk: getRenderChunk({
      minify: true,
      sourceMap,
      ...options,
}),

When using Vue 3, a compilation error occurred in <></> in tsx

Configuration used in the plugin

plugins: [
    vueJsx(),
    esbuild({ 
      jsxFactory: 'vueJsxCompat',
     }),
    vue(),
]

Use in code

const CardContainer = defineComponent({
    setup(props) {
      return () => <> text </>
    }
})

Compiled results

const CardContainer = defineComponent({
      setup(props2) {
        return () => /* @__PURE__ */ vueJsxCompat(React.Fragment, null, " text ");
      }
});

image

Add bundle option

eslint has a bundle: true|false (default: false) option. it would be useful to have this option in this rollup plugin as well. the option also replaces @rollup/plugin-node-resolve if i'm not mistaken.

[bug] Using TypeScript decorators throws an error

Thank you for publishing this very useful package.

Given this file at packages/docs/copy-code.ts

show copy-code.ts
import { customElement, html, internalProperty, LitElement } from 'lit-element'

import ButtonStyles from './button.css';
import CopyStyles from './copy.css';

const supportsClipboard = 'clipboard' in navigator;

@customElement('copy-code')
export class CopyCode extends LitElement {
  static readonly is = 'copy-code';

  static readonly styles = [ButtonStyles, CopyStyles];

  @internalProperty() copyButtonText = 'Copy';

  render() {
    return html`
      <slot></slot>

      <button id="copy-button"
          @click="${this.onCopy}"
          ?hidden="${!supportsClipboard}"
          data-bold="Copied ✅">
        ${this.copyButtonText}
      </button>
    `;
  }

  async onCopy() {
    const { textContent } = this;
    await navigator.clipboard.writeText(textContent.trim());
    this.copyButtonText = 'Copied ✅';
    setTimeout(() => {
      this.copyButtonText = 'Copy';
    }, 2000);
  }
}

and this file at packages/docs/tsconfig.json

{
  "compilerOptions": {
    "target": "ES2019",
    "module": "ESNext",
    "useDefineForClassFields": false,
    "importHelpers": true,
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "sourceMap": true,
    "moduleResolution": "Node"
  }
}

and this file at rollup.config.docs.js

/* eslint-env node */
import esbuild from 'rollup-plugin-esbuild';
import nodeResolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import litcss from 'rollup-plugin-lit-css';

export default {
  input: './packages/docs/copy-code.ts',
  output: {
    format: 'es',
    file: './docs/components.js',
  },
  plugins: [
    litcss(),
    esbuild({
      target: 'es2017',
      minify: true,
      sourceMap: true,
      loaders: {
        '.ts': 'ts',
        '.css': 'js',
        '.graphql': 'js',
      },
    }),
    nodeResolve(),
    commonjs(),
  ],
};

when running rollup -c rollup.config.docs.js, I get this error:

yarn run v1.18.0
$ rollup -c rollup.config.docs.js

./packages/docs/components.ts → ./docs/components.js...
[!] Error: Unexpected character '@' (Note that you need plugins to import files that are not JavaScript)
packages/docs/copy-code.ts (8:0)
 6: const supportsClipboard = 'clipboard' in navigator;
 7: 
 8: @customElement('copy-code')
    ^
 9: export class CopyCode extends LitElement {
10:   static readonly is = 'copy-code';
Error: Unexpected character '@' (Note that you need plugins to import files that are not JavaScript)
    at error (/Users/bennyp/Documents/apollo-elements/node_modules/rollup/dist/shared/rollup.js:5251:30)
    at Module.error (/Users/bennyp/Documents/apollo-elements/node_modules/rollup/dist/shared/rollup.js:9810:16)
    at tryParse (/Users/bennyp/Documents/apollo-elements/node_modules/rollup/dist/shared/rollup.js:9691:23)
    at Module.setSource (/Users/bennyp/Documents/apollo-elements/node_modules/rollup/dist/shared/rollup.js:10114:19)
    at ModuleLoader.addModuleSource (/Users/bennyp/Documents/apollo-elements/node_modules/rollup/dist/shared/rollup.js:18275:20)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at ModuleLoader.fetchModule (/Users/bennyp/Documents/apollo-elements/node_modules/rollup/dist/shared/rollup.js:18331:9)
    at async Promise.all (index 0)
    at ModuleLoader.fetchStaticDependencies (/Users/bennyp/Documents/apollo-elements/node_modules/rollup/dist/shared/rollup.js:18356:34)
    at async Promise.all (index 0)

error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

I would expect this to compile just fine

TSConfig Containing dangling `,` in array fails to parse

Example tsconfig:

{
     "compilerOptions": {
         "lib": [
             "Something",
             "something else",
         ]
      }
}

This is perfectly fine for jsonc however throws an error when parsing using this plugin. Looking in the code I see that this plugin gets the configuration, strips the JSON comments and simply passes through JSON.parse.

I can submit a PR but unsure what you would like to do here? Either using a compatible json parser or somehow stripping the dangling ,.

Generated sourcemap maybe broken

I think the generated sourcemap is probably broken.

Environment

name version
Node.js 14.19.0 / 16.13.2
esbuild 0.14.18
rollup 2.67.0
rollup-plugin-esbuild 4.8.2

Procedure for reproducing

  1. Prepare a simple TypeScript file as shown below.

    index.ts
    export function print1() {
        console.log(1);
    }
    
    export function print2() {
        console.log(2);
    }
    
    export function print3() {
        console.log(3);
    }
  2. Transpile it with the rollup config file like the following.

    rollup.config.js
    import esbuild from 'rollup-plugin-esbuild';
    
    export default [
        {
            input: './src/index.ts',
            output: {
                file: './dist/index.js',
                format: 'cjs',
                sourcemap: true,
            },
            plugins: [
                esbuild({
                    target: 'es2020',
                    // sourcemap: true,
                }),
            ],
        },
    ];
  3. The following index.js.map is generated with index.js, but it seems to be broken.

    {"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["export function print1() {\n    console.log(1);\n}\n\nexport function print2() {\n    console.log(2);\n}\n\nexport function print3() {\n    console.log(3);\n}\n"],"names":[],"mappings":";;;;AAAO,SAAS,MAAM,GAAG;AACzB,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;AACjB,CAAC;AACM,SAAS,MAAM,GAAG;AACzB,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;AACjB,CAAC;AACM,SAAS,MAAM,GAAG;AACzB,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;AACjB;;;;;;"}

    You can check if the SourceMap is correct by using a tool like "Source Map Visualization".


Note that the sourcemap is correct when building with esbuild alone, without rollup and its plugins.
I apologize if this is my misunderstanding or incorrect usage.
Best regards,

Minimizing css

Hey,

Im using esbuild-loader in webpack and in projects that i use rollup i want to use your plugin, but i noticed that esbuild-loader has css: true option to minify css, and its not present in your plugin. Its not minifying css by default, and i would really like to keep dependencies to a minimum, and thats a good opportunity to do that, apart from speeding things up.

Is there a plan for adding this boolean to forward it to esbuild?

More info:
https://github.com/privatenumber/esbuild-loader/blob/develop/README.md#css-assets

`experimentalBundling: true` ignores `define` object

I've made a branch to demonstrate experimentalBundling not using the define config object

First I added an extra task to package.json, which uses a different config file to the current example

"example:experimental": "npm run build && rollup -c example/rollup.config.experimental.js",

rollup.config.js remains unchanged (except for disabling minify)

rollup.config.experimental.js looks like this -

const esbuild = require('../dist/index')

export default {
  input: 'example/index.js',
  output: {
    file: 'example/dist/index.experimental.js', // different output filename
    format: 'cjs',
  },
  plugins: [
    esbuild({
      experimentalBundling: true, // enable experimental
      minify: false,
      define: {
        'process.env.MESSAGE': `"${process.env.MESSAGE}"`,
      },
    }),
  ],
}

I then ran -

MESSAGE='hello from env'  npm run example
MESSAGE='hello from env'  npm run example:experimental

the output of the regular build was as expected

'use strict';

class Foo {
  render() {
    return /* @__PURE__ */ React.createElement("div", {
      className: "hehe"
    }, "hello from env");
  }
}

console.log(Foo);

but the experimental build output had not swapped in the "hello from env" message

'use strict';

// example/foo.tsx
var Foo = class {
  render() {
    return /* @__PURE__ */ React.createElement("div", {
      className: "hehe"
    }, process.env.MESSAGE);
  }
};
var foo_default = Foo;

// example/index.js
console.log(foo_default);

Minify format option

Currently the esbuild format option is always set using getEsbuildFormat() for IIFE it will result in double wrapping the already created IIFE function by rollup. Example:

(() => {(function(o){ ... })})();

Removing the format option will fix the issue. I rollup already takes care defining an output format, so its not needed to do it again in esbuild minify.

add vue jsx transformer to esbuild

i was use rollup-plugin-esbuild to my vue3-components

but i found it`s to hard to work with vue-jsx. it always need transform

here is my transformer vueJsxCompat.ts , copy form vite

After this step, all my .tsx files will add

// add this line for vue-jsx
import { vueJsxCompat } from '../vue-jsx-compat';

other users repo nova-next also have same problem, all the .tsx files will add this code

so i work with another plugin rollup-plugin-vue-jsx-compat

here is the config

const vueJsx = require("../dist/index");
const esbuild = require("rollup-plugin-esbuild");

export default {
  input: 'example/index.js',
  output: {
    file: 'example/dist/index.js',
    format: 'cjs',
  },
  plugins: [
    vueJsx(),
    esbuild({
      jsxFactory: "vueJsxCompat"
    }),
  ],
}

i was wandering is this alpha-code design correct, and you may consider adding this feature to your project ?

sourceMap property broken

import esbuild from "rollup-plugin-esbuild";

export default {
  input: "src/mod.ts",
  plugins: [
    esbuild({
      watch: process.argv.includes("--watch"),
      minify: process.env.BUILD === "production",
      sourceMap: true,
    }),
  ],
  output: {
    dir: "dist",
    format: "esm",
  },
};
[!] (plugin esbuild) Error: Transform failed with 1 error:
error: Must use "sourcefile" with "sourcemap" to set the original file name

but the following seems to work, is this config correct? It is not using the extension as show in the README:

import esbuild from "rollup-plugin-esbuild";

export default {
  input: "src/mod.ts",
  plugins: [
    esbuild({
      watch: process.argv.includes("--watch"),
      minify: process.env.BUILD === "production",
    }),
  ],
  output: {
    dir: "dist",
    format: "esm",
    sourcemap: true,
  },
};

Here is my tsconfig,json in case it helps:

{
  "compilerOptions": {
    "target": "es2019",
    "module": "ESNext",
    "moduleResolution": "node",
    "sourceMap": true,
    "strict": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true
  },
  "include": ["src/**/*.ts", ".eslintrc.js", "rollup.config.js"],
  "exclude": ["node_modules"]
}

Extend esbuild types

Hey @egoist,

Thanks for your all your OS work and bringing support for esbuild to Rollup. Looking over the code the way in which types are applied could be improved. Folks tend to rely heavily on Intellisense capabilities within editors and as we see in #331 devs will assume something it not supported when an option is not made available in completions.

We only need to omit the CommonOptions that this plugin does not support. Here is a refined approach you could leverage that will extend the ESBuild types, opposed to the interface used in index.ts

Let me know if you need a PR and I try get around to it.

import type { CommonOptions, Loader } from 'esbuild';

type OmitOptions = Omit<CommonOptions, (
  | 'sourcesContent'
  | 'sourcemap'
  | 'sourceRoot'
  | 'color'
  | 'logLevel'
  | 'logLimit'
)>

type MinifyOptions = Omit<OmitOptions, (
  | 'format'
  | 'sourcesContent'
  | 'globalName'
  | 'define'
  | 'pure'
  | 'jsx'
  | 'jsxFactory'
  | 'jsxFragment'
)>

export interface ESBuildOptions extends OmitOptions {
  sourceMap?: boolean;
  optimizeDeps?: MarkOptional<OptimizeDepsOptions, 'cwd' | 'sourceMap'>
  /**
   * Use this tsconfig file instead
   * Disable it by setting to `false`
   */
  tsconfig?: string | false;
  /**
   * Map extension to esbuild loader
   * Note that each entry (the extension) needs to start with a dot
   */
  loaders?: {
    [ext: string]: Loader | false;
  };
}

SyntaxError: The requested module 'es-module-lexer' does not provide an export named 'default'

src/optimizer/optmize-deps.ts uses es-module-lexer' which says gives the following error in unbuild

yarn run v1.22.15
$ unbuild
[hidden]/ual-wax/node_modules/rollup-plugin-esbuild/dist/index.mjs:125
import esModuleLexer from "es-module-lexer";
       ^^^^^^^^^^^^^
SyntaxError: The requested module 'es-module-lexer' does not provide an export named 'default'
    at ModuleJob._instantiate (internal/modules/esm/module_job.js:121:21)
    at async ModuleJob.run (internal/modules/esm/module_job.js:166:5)
    at async Loader.import (internal/modules/esm/loader.js:178:24)
    at async Object.loadESM (internal/process/esm_loader.js:68:5)
error Command failed with exit code 1.

Support for --keep-names

--keep-names seems to have no effect upon inspecting the output bundle generated with the following config:

const plugins = [
  commonjs(),
  resolve(),
  esbuild({
    include: /\.ts$/,
    exclude: /node_modules|tests/,
    sourceMap: true,
    minify: true,
    keepNames: true,
    target: "esnext",
    tsconfig: "tsconfig.json"
  })
];
export default {
  input: "src/index.ts",
  output: { file: "dist/core.esm.js", format: "esm", sourcemap: true },
  plugins
};

Does it also replace rollup-plugin-babel?

The read says that:

this plugin replaces rollup-plugin-typescript2, @rollup/plugin-typescript and rollup-plugin-terser for you.

Does it also replace rollup-plugin-babel?

Support plugins / inject

Hey, nice plugin! :)

Would be nice if plugins was supported. It would help a lot with React 17 and automatic jsx runtime.

Thanks!

Good stuff.

This worked out of the box and it took about 40% off of my build time.
Good stuff.

[feature] log error details/context to console

Currently utilizing this plugin in my Vue app build process and I keep getting very vague error indications making this process virtually useless...

bundles client/main.js → public\assets\bundle.js...
[!] (plugin esbuild) Error: Transform failed with 1 error
client\store\auth.js
Error: Transform failed with 1 error
    at failureErrorWithLog (C:\github\my-watch-list\node_modules\esbuild\lib\main.js:62:17)
    at Object.transform (C:\github\my-watch-list\node_modules\esbuild\lib\main.js:279:38)
    at processTicksAndRejections (internal/process/task_queues.js:86:5)

I'm doing some more research into ESBuild in general, however it's unacceptable that this tool should warn me of errors and give me zero context for where the error was actually found...

The documentation doesn't mention anything about a verbose mode either.

esbuild is listed as `devDependency`

I noticed esbuild is listed as devDependency despite being a true dependency, is this done intentionally for some specific reason I might be unaware of, or is this an oversight?

Async/await code can lead to undefined `this` references being emitted

joeally/rollup-esbuild-await-this-bug demonstrates a minor bug with rollup-plugin-esbuild that sees it give a confusing error message in some circumstances when using async/await code.

An example of some code that will cause such a warning can be found in src/index.ts and is shown below:

export const myAsyncFunction = async (): Promise<void> => {
	await Promise.resolve('hello');
}

When bundling with Rollup and rollup-plugin-esbuild this will result in the following warning:

(!) Error when using sourcemap for reporting an error: Can't resolve original location of error.
src/index.ts (21:45)
(!) `this` has been rewritten to `undefined`
https://rollupjs.org/guide/en/#error-this-is-undefined
src/index.ts
19:   });
20: };
21: export const myAsyncFunction = () => __async(this, null, function* () {
                                                 ^
22:   yield Promise.resolve("hello");
23: });
created dist/main.cjs, dist/main.mjs in 39ms

This doesn't cause any issues in terms of the generated code's functionality but it is confusing.

It doesn't seem to be an issue with esbuild itself since calling esbuild without rollup generates the following (run yarn run esbuildOnly to see for yourself):

// ... the __async helper function definition will be here but removed for clarity

// src/index.ts
var myAsyncFunction = () => __async(void 0, null, function* () {
  yield Promise.resolve("hello");
});
export {
  myAsyncFunction
};

As you can see above esbuild seems to output void 0 and not this. So the issue must be with rollup-plugin-esbuild

Invalid option "jsx" due to old esbuild version.

We are working in a monorepo and using rollup with this plugin for building our modules, however we started getting this error:
Error: Transform failed with 1 error: error: Invalid option in transform() call: "jsx"

I debugged both the plugin and esbuild and found out that the issue was caused due to the plugin adding a "jsx" option which isn't supported in the esbuild version noted in the plugin's pacakge.json.
I was able to solve it by manually installing the latest version of esbuild, but I think that its best to also update the version the the plugin's pacakge.json.

rollup-plugin-esbuild version: 4.5.0
esbuild in the plugin's package.json: 0.12.5
My esbuild version: 0.12.7

Filename extension .ts required?

Hi 👋

First, thank you for your plugin!

I have Svelte TS project and I'm trying to replace rollup/plugin-typescript, rollup/plugin-sucrase and rollup-plugin-terser by esbuild and your plugin.
However, I'm stumbling upon an error that tells me to add .ts in every import done with an alias in my files to make them work.

The import:

<script lang="typescript">
  import { localStorageKeys } from '@utils/localStorageKeys';

Extract of the rollup conf:

  plugins: [
    alias({
      entries: [
        {
          find: '@utils',
          replacement: path.resolve(projectRootDir, 'src/utils'),
        }
      ],
    }),
    esbuild({
      sourceMap,
      minify: production,
      loaders: {
        '.js': 'js',
        '.ts': 'ts',
        '.json': 'json',
      },
    })
]

And the error:

[!] Error: Could not load /src/utils/localStorageKeys (imported by src/App.svelte): ENOENT: no such file or directory, open /src/utils/localStorageKeys'

The error goes away by adding .ts extension to the import.


However, it seems to work if I dont use my aliases, this gives me no error.

import { localStorageKeys } from './utils/localStorageKeys';

My question is, is this intended as normal behavior or did I missed something?

esbuild v0.9: startService is being removed

Esbuild v0.9 is just released with breaking changes. One of them is that starService function is being removed. Instead, we should use transform or build function directly.

[bug] dist/index.js missing in v1.5.0

The dist/index.js file is missing in the v1.5.0 release resulting in

[!] Error: Cannot find module '/path/to/node_modules/rollup-plugin-esbuild/dist/index.js'. Please verify that the package.json has a valid "main" entry

[Feature Request]: Add an option for setting `charset`

Background:

I am using this plugin to compile one of my locale file which contains utf-8 charset instead of simple ascii word.

Example

Say we have this file:

locale.zh_CN.ts

export default {
  picker: {
    confirm: "确定",
    clear: "清除",
  },
  // ...
}

If I run the compiler with options:

build.js

const path = require('path')
const { nodeResolve } = require('@rollup/plugin-node-resolve')
const rollup = require('rollup')
// const typescript = require('rollup-plugin-typescript2')
const esbuild = require('rollup-plugin-esbuild')

const root = path.resolve(__dirname, '..');
const file = process.argv[2];
const defaultOpts = {
  input: path.resolve(root, file),
  plugins: [
    nodeResolve(),
    esbuild()
  ],
  external() {
    return true
  },
}

const run = async (name) => {
  const esm = {
    format: 'es',
    file: `es/${name}`,
  };
  const cjs = {
    format: 'cjs',
    file: `lib/${name}`,
    exports: 'named',
  }

  const bundle = await rollup.rollup(defaultOpts);
  await Promise.all([bundle.write(esm), bundle.write(cjs)]);
  console.log(name, 'build finished');
}

run(`locale.zh_CN.ts`)

Which produces:

export default {
  colorpicker: {
    confirm: "\u786E\u5B9A",
    clear: "\u6E05\u7A7A"
  }
}

Suggestion

Per Charset for esbuild, esbuild allows user to pass an option called charset.
Should we add an option for users to pass charset to esbuild ?

Support for loaders in options

My project has jsx in .js files.
I see that its not configurable in the options and that its passed according to the extension of the file.
Please enable this support and that would make this plugin usable for us.

Add option to pass through (parsed) tsconfig to avoid resolving the configuration in the transform step for every file

So I have a configuration that essentially adds every ts file in my project as an entry point. This plugin is of course perfectly capable of dealing with that however I notice that it's resolving the tsconfig and parsing it in the transform step.

What would be nice is if there was an option to pass through an already parsed tsconfig file to the plugin to essentially make it clear I do not have a different configuration for every single file.

On top of that to make the whole parsing easier, this library could expose a utility function to load the tsconfig so you can pass it directly through to the options.

For example proposed API:

import esbuild, { loadTypescriptConfiguration } from 'rollup-plugin-esbuild';

/// ... rollup etc
esbuild({
    fullTsConfig: loadTypescriptConfiguration('./tsconfig.json),
});

Alternatively an option to just use the first tsconfig it finds when the plugin is loaded would be fine too.

[feature] add loader to options

Thanks for creating this plugin!

I've encountered a project where the files have a .js suffix but they're actually jsx format. It's fairly common for react projects. I couldn't find an existing option to set this. Patching the installed plugin to allow overriding the loader does the trick:

--- a/node_modules/rollup-plugin-esbuild/dist/index.js
+++ b/node_modules/rollup-plugin-esbuild/dist/index.js
@@ -54,4 +54,4 @@
       const result = await service.transform(code, {
-        loader,
-        target: options.target || "es2015",
+        loader: options.loader || loader,
+        target: options.target || "es2019",
         jsxFactory: options.jsxFactory,

I'd also recommend to up the default target to "es2019" since some TS features do not map correctly to ES2015 in esbuild.

Edit: patch updated

`ts-essentials` is listed as a `devDependency`

However, dist/index.d.ts does import { MarkOptional } from 'ts-essentials';, which leads to

node_modules/rollup-plugin-esbuild/dist/index.d.ts:3:30 - error TS2307: Cannot find module 'ts-essentials' or its corresponding type declarations.

3 import { MarkOptional } from 'ts-essentials';
                               ~~~~~~~~~~~~~~~

because

declare type Options = {
    /* ... */
    optimizeDeps?: MarkOptional<OptimizeDepsOptions, 'cwd' | 'sourceMap'>;

rollup-plugin-dts cannot generate d.ts but only roll-up d.ts

Hi, I'm trying use this plugin in my project, but I can't find a way to generate d.ts, it seems that rollup-plugin-esbuild delegates the task of generating d.ts to the user or other plugins (rollup-plugin-dts).

But I can not find a way to generate d.ts in rollup-plugin-dts either 🤣

Race condition fails the build with multiple chunks + minify

Preconditions: production build with minify: true and multiple output in the rollup config (I use one for modern browsers, and one for legacy browsers that instead will use the systemjs format)

The plugin prematurely closes the esbuild service while esbuild is still processing the second chunk/request, as seen in these logs:

image

It seems like generateBundle (and thus, stop()) is called before the second Promise for renderChunk resolved. The esbuild service should probably be treated like a shared dependency (global state) for all chunks and only be stopped when all chunks are done?

Loader options are behaving strangely

Hi, thanks for the excellent plugin, I think it will get a lot of attention and usage very soon.
I tried to compile a boilerplate for a WebGL project the other day, and had a lot of problems with the loaders. It seems like the loaders option actually expect the file extensions without a dot. You can check it out on a dummy repository I've created here https://github.com/w8r/rollup-typescript-esbuild

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.