bpceee / bpceee.github.io

My blog posts
https://bpceee.github.io/
2 stars 1 forks source link

A bizarre pitfall when converting CommonJS to ES6 module #8

Open bpceee opened 5 years ago

bpceee commented 5 years ago

Well, it wouldn't be bizarre if you really know inside out of Webpack and ES6 module..

As we all know, @font-face defined in css will trigger a http request for the font file based on the url() CSS function. However, after updated to ES6 module, the url somehow doesn't value the __webpack_public_path__ set in the entry point app.ts. Thus, many failed font requests.

Well, the reason is that import statements are always hoisted in es6 module, so the __webpack_public_path__ initialization in the first line of app.ts didn't have any effects in those hoisted import statements including the css file. So, after putting the __webpack_public_path__ initialization into a separation file and get it imported into app.ts, problem resolved!

// app.ts
import "./public-path";
import "./index.css";
// public-path.ts
__webpack_public_path__ = "..."