Comments (1)
Hi! I hit the same bug while was working on my library that needs to be compiled to both esm and cjs modules (https://github.com/Edgar-P-yan/node-systray-v2/). The shims are inserted in the middle of other import statements causing syntax errors. But i didn't have any commented import
keywords. So probably the ESMStaticImportRegex has other bugs in it too. The version i'm using is the latest at this moment (v0.1.6). Here is the result:
import * as child from 'child_process';
import * as readline from 'readline';
import * as path from 'path';
import * as os from 'os';
import * // <-- The import statement is cut in the middle
// -- Shims --
import cjsUrl from 'node:url';
import cjsPath from 'node:path';
import cjsModule from 'node:module';
const __filename = cjsUrl.fileURLToPath(import.meta.url);
const __dirname = cjsPath.dirname(__filename);
const require = cjsModule.createRequire(import.meta.url);
as fs from 'fs-extra'; // <-- The unfinished import continues after the inserted shims
import { EventEmitter } from 'events';
import xdebug from 'debug';
So i wanted to share a simple and temporary solution to this, a slightly modified version of this plugin. This will also not work for commented import statements, but at least the regex is simpler, so you can adjust it. See the comments for more info about patches:
/**
* An alternative to @rollup/plugin-esm-shim (https://github.com/rollup/plugins/tree/master/packages/esm-shim).
*
* The original ESM shim plugin has a bug: it inserts the shims
* in wrong places causing syntax errors. This slightly modified
* version of it is a very simple solution, which surely will not work
* in every case, but at list does not brake specifically for my code.
*
* Whats different from the original?
* The regex used to find import statements is changed to a more
* simple one /^import\s.*';$/gm and the whole logic is a lot simpler,
* so you can adjust the regex to make it work with your code, if it suddenly doesn't.
*/
function esmShimCustom() {
const ESMShim = `
// -- Shims --
import cjsUrl from 'node:url';
import cjsPath from 'node:path';
import cjsModule from 'node:module';
const __filename = cjsUrl.fileURLToPath(import.meta.url);
const __dirname = cjsPath.dirname(__filename);
const require = cjsModule.createRequire(import.meta.url);
// -- End Shims --
`;
const CJSyntaxRegex = /__filename|__dirname|require\(|require\.resolve\(/;
return {
name: 'esm-shim-custom',
renderChunk(/** @type {string} */ code, _chunk, opts) {
if (opts.format === 'es') {
if (code.includes(ESMShim) || !CJSyntaxRegex.test(code)) {
return null;
}
let endIndexOfLastImport = -1;
// Find the last import statement and its ending index
for (let match of code.matchAll(/^import\s.*';$/gm)) {
if (match.length === 0 || typeof match.index !== 'number') {
continue;
}
endIndexOfLastImport = match.index + match[0].length;
}
const s = new MagicString(code);
s.appendRight(endIndexOfLastImport, ESMShim);
const sourceMap = s.generateMap({
includeContent: true,
});
/** @type {string[] | undefined} */
let sourcesContent;
if (Array.isArray(sourceMap.sourcesContent)) {
sourcesContent = [];
for (let i = 0; i < sourceMap.sourcesContent.length; i++) {
const content = sourceMap.sourcesContent[i];
if (typeof content === 'string') {
sourcesContent.push(content);
}
}
}
return {
code: s.toString(),
map: {
...sourceMap,
sourcesContent,
},
};
}
return null;
},
};
}
And the usage is straight-forward, just copy the function esmShimCustom
provided above into your rollup.config.js
, and add it to output.plugins
:
const options = {
output: [
{
banner,
name: 'node-systray-v2',
exports: 'named',
sourcemap: true,
file: './dist/index.mjs',
format: 'esm',
plugins: [esmShimCustom()], // <-- insert it right here
},
...
],
...
}
from plugins.
Related Issues (20)
- Watch mode: multiple saves required for changes to be transpiled correctly HOT 1
- (Compilation) error RollupError: Expected '{', got 'interface' / token 'static' . Expected * for generator, private key, identifier or async HOT 2
- [@rollup/plugin-commonjs]: vulnerability in inflight
- [@rollup/plugin-commonjs]: Which Comes First?The Documentation Seems to Be Conflicting
- [@rollup/plugin-replace] Missing sourceMap option within Readme HOT 2
- (@rollup/plugin-typescript) Cannot import typescript file from parent folder (../script) without .ts file extension (../script.ts)
- [!] (plugin typescript) RollupError: [plugin typescript] @rollup/plugin-typescript: Path of Typescript compiler option 'outDir' must be located inside Rollup 'dir' option.
- [@rollup/plugin-typescript] Cannot resolve input filepath which is absolute path and begin with lower case drive letter on windows
- [@rollup/plugin-node-resolve] Allow fallbacks for dependencies with incorrect exports field on package.json
- @rollup/plugin-alias entries is not work when use customResolver HOT 1
- [@rollup/plugin-eslint] New flat config `eslint.config.js` is not recognized
- [@rollup/plugin-node-resolve] confusion about what this plugin does HOT 2
- How to tell `--configPlugin` to use specific `tsconfig`? HOT 4
- [@rollup/plugin-node-resolve] resolving package.json exports/imports arrays
- Source URLs in generated source map are wrong when `composite` is enabled in tsconfig.json
- requireReturnsDefault: "auto" results in an incorrect bundle for some libraries
- [@rollup/plugin-alias] Allow to configure alias based on entry point
- 在SCSS中如何替换Var变量
- Allow @rollup/plugin-virtual to be a function that takes a module ID
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from plugins.