Friday, 5 February 2021

Natively import ES module dependencies from npm without bundling/transpiling first-party source

Background

I'm trying to create a "buildless" JavaScript app, one where I don't need a watch task running to transpile JSX, re-bundle code, etc every time I save any source file.

It works fine with just first-party code, but I'm stuck when I try to import dependencies from npm.

Goal

I want to achieve this kind of workflow:

  1. npm install foo (assume it's an ES module, not CommonJS)
  2. Edit source/index.js and add import { bar } from 'foo'
  3. npm run build. Something (webpack, rollup, a custom script, whatever) runs, and bundles foo and its dependencies into ./build/vendor.js (without anything from source/).
  4. Edit index.html to add <script src="build/vendor.js" type="module"...
  5. I can reload source/index.js in my browser, and bar will be available. I won't have to run npm run build until the next time I add/remove a dependency.

I've gotten webpack to split dependencies into a separate file, but to import from that file in a buildless context, I'd have to import { bar } from './build/vendor.js. At that point webpack will no longer bundle bar, since it's not a relative import.

I've also tried Snowpack, which is closer to what I want conceptually, but I still couldn't configure it to achieve the above workflow.

I could just write a simple script to copy files from node_modules to build/, but I'd like to use a bundled in order to get tree shaking, etc. It's hard to find something that supports this workflow, though.



from Natively import ES module dependencies from npm without bundling/transpiling first-party source

No comments:

Post a Comment