Skip to content

Commit e72d34d

Browse files
authored
fix(cjs-build): enable evaluating import.meta in cjs build (#1236)
## Purpose A while ago, a [PR](#897) was merged to disable `import.meta` evaluation altogether to support new versions of Webpack. This sometimes causes issues in CJS projects. In the comments, there were some [discussions](#897 (comment)) about whether we should have a conditional and keep the previous behavior for CJS builds. This PR addresses exactly this by translating `import.meta.url` to a CJS compatible statement which results to the same output. I have created a [comparative build](https://github.com/meienberger/ncc/pull/1/files) between two projects using the same code and a dependency (@sentry/node) that uses `import.meta.url`. You can see the difference in the output `index.js` Before the change: ```javascript const importMetaUrl = typeof import.meta.url !== 'undefined' ? import.meta.url : undefined; ``` After: ```javascript const importMetaUrl = typeof require("url").pathToFileURL(__filename).href !== 'undefined' ? require("url").pathToFileURL(__filename).href : undefined; ``` Closes #1019
1 parent 186af2b commit e72d34d

4 files changed

Lines changed: 28 additions & 0 deletions

File tree

src/index.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,12 @@ function ncc (
252252
}));
253253
}
254254

255+
if (!esm) {
256+
plugins.push(new webpack.DefinePlugin({
257+
'import.meta.url': 'require("url").pathToFileURL(__filename).href'
258+
}));
259+
}
260+
255261
const compiler = webpack({
256262
entry,
257263
cache: cache === false ? undefined : {

test/unit/import-meta-cjs/input.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
console.log(import.meta.url);
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
/******/ (() => { // webpackBootstrap
2+
/******/ /* webpack/runtime/compat */
3+
/******/
4+
/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/";
5+
/******/
6+
/************************************************************************/
7+
var __webpack_exports__ = {};
8+
console.log(require("url").pathToFileURL(__filename).href);
9+
/******/ })()
10+
;
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
/******/ (() => { // webpackBootstrap
2+
/******/ /* webpack/runtime/compat */
3+
/******/
4+
/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/";
5+
/******/
6+
/************************************************************************/
7+
var __webpack_exports__ = {};
8+
console.log(require("url").pathToFileURL(__filename).href);
9+
module.exports = __webpack_exports__;
10+
/******/ })()
11+
;

0 commit comments

Comments
 (0)