Skip to content

Commit

Permalink
fix: use custom Rollup plugin for import.meta.url (#77)
Browse files Browse the repository at this point in the history
* fix: use custom Rollup plugin for `import.meta.url`

Refs eslint/eslint#15766

* Use URL#toString()

Co-authored-by: 唯然 <weiran.zsd@outlook.com>

Co-authored-by: 唯然 <weiran.zsd@outlook.com>
  • Loading branch information
mdjermanovic and aladdin-add committed Apr 21, 2022
1 parent a6e12e4 commit 18b15ac
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 3 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Expand Up @@ -107,3 +107,6 @@ dist
yarn.lock
package-lock.json
pnpm-lock.yaml

# used in tests
/tmp/
2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -59,7 +59,7 @@
"eslint-release": "^3.2.0",
"fs-teardown": "^0.1.3",
"mocha": "^9.0.3",
"rollup": "^2.54.0",
"rollup": "^2.70.1",
"shelljs": "^0.8.4",
"sinon": "^11.1.2",
"temp-dir": "^2.0.0"
Expand Down
22 changes: 21 additions & 1 deletion rollup.config.js
@@ -1,3 +1,22 @@
/**
* Custom Rollup plugin for `import.meta.url` transformation to commonjs.
* The default transformation ('file:' + __filename) does not check characters in __filename,
* and thus can produce invalid URLs, like in https://github.com/eslint/eslint/issues/15766
* See https://github.com/eslint/eslint/issues/15766#issuecomment-1093941321
* @returns {Object} Rollup plugin object.
*/
function importMetaURLPlugin() {
return {
name: "custom-import-meta-url",
resolveImportMeta(property) {
if (property === "url") {
return "require('url').pathToFileURL(__filename).toString()";
}
return null;
}
};
}

export default [
{
input: "./lib/index.js",
Expand All @@ -12,7 +31,8 @@ export default [
file: "dist/eslintrc.cjs",
sourcemap: true,
freeze: false
}
},
plugins: [importMetaURLPlugin()]
},
{
input: "./lib/index-universal.js",
Expand Down
21 changes: 20 additions & 1 deletion tests/lib/commonjs.cjs
Expand Up @@ -12,7 +12,8 @@
const assert = require("assert");
const eslintrc = require("../../dist/eslintrc.cjs");
const universal = require("../../dist/eslintrc-universal.cjs");

const path = require("path");
const sh = require("shelljs");

//------------------------------------------------------------------------------
// Tests
Expand Down Expand Up @@ -73,3 +74,21 @@ describe("eslintrc CommonJS Universal", () => {
});
});
});

// https://github.com/eslint/eslint/issues/15766
describe("eslintrc CommonJS loading", () => {
const testDir = path.resolve(__dirname, "../../tmp/my%2Fproject");

before(() => {
sh.mkdir("-p", testDir);
sh.cp("", "./dist/eslintrc.cjs", testDir);
});

after(() => {
sh.rm("-r", testDir);
});

it("eslintrc.cjs module successfully loads when it is in a path that contains URL-encoded characters", () => {
require(path.resolve(testDir, "eslintrc.cjs"));
});
});

0 comments on commit 18b15ac

Please sign in to comment.