ephem / rollup-plugin-preserve-directives Goto Github PK
View Code? Open in Web Editor NEWA Rollup plugin to preserve directives like "use client" when preserveModules is true
License: MIT License
A Rollup plugin to preserve directives like "use client" when preserveModules is true
License: MIT License
I think magic-string should be in the regular dependencies (not dev) but I'm not sure.
Hi, first of all thanks for the amazing work, this helped me a lot!
I don't think this is actually a bug, but it might help someone and also, I wanted to ask if the way I solved it is the correct one.
I'm using Vanilla Extract, React and Vite to build a component library. While trying to add support for RSC I encountered the issue that this library fixes, but the problem is that VE generates CSS files during build time, so when running the transform phase, specifically when calling the Acorn instance (const ast = this.parse(code);
) it throws an error because it can't parse a css.(cjs/js) file (this is the part I don't really understand why. Thought it made sense but checking in detail each file, it should be able to parse it I guess?). My simple and naive solution was to just avoid parsing these files by adding the following code in the transform hook:
if (/.\.css$/.test(id)) {
return { code, map: null };
}
If there is a better solution and/or this is a change that could be applied to this package please let me know, else I hope this helps someone in the same situation!
Thanks again for this plugin!
When using this plugin and importing an SVG file for inclusion, rollup fails to build. Removal of the SVG file allows things to build normally again. Please advise.
import MyLogoSVG from '../../assets/images/logo.svg';
The error:
[!] (plugin preserve-directives) SyntaxError: Unexpected token (1:0)
src/assets/images/logo.svg (1:0)
at Parser.pp$4.raise (/Users/mirigoye/Code/ids/node_modules/rollup/dist/shared/rollup.js:22778:13)
at Parser.pp$9.unexpected (/Users/mirigoye/Code/ids/node_modules/rollup/dist/shared/rollup.js:19989:8)
at Parser.pp$5.parseExprAtomDefault (/Users/mirigoye/Code/ids/node_modules/rollup/dist/shared/rollup.js:22149:8)
at Parser.pp$5.parseExprAtom (/Users/mirigoye/Code/ids/node_modules/rollup/dist/shared/rollup.js:22144:17)
at Parser.pp$5.parseExprSubscripts (/Users/mirigoye/Code/ids/node_modules/rollup/dist/shared/rollup.js:21928:19)
at Parser.pp$5.parseMaybeUnary (/Users/mirigoye/Code/ids/node_modules/rollup/dist/shared/rollup.js:21894:17)
at Parser.pp$5.parseExprOps (/Users/mirigoye/Code/ids/node_modules/rollup/dist/shared/rollup.js:21821:19)
at Parser.pp$5.parseMaybeConditional (/Users/mirigoye/Code/ids/node_modules/rollup/dist/shared/rollup.js:21804:19)
at Parser.pp$5.parseMaybeAssign (/Users/mirigoye/Code/ids/node_modules/rollup/dist/shared/rollup.js:21771:19)
at Parser.pp$5.parseExpression (/Users/mirigoye/Code/ids/node_modules/rollup/dist/shared/rollup.js:21734:19)
On vacation but creating a quick summary of this just so it's tracked in public. Error messages sometimes seems to come from this plugin when it's not actually the cause, and have less detail than they should, when it's the first plugin that parses the AST.
Sometimes reordering plugins helps, sometimes removing this plugin gives a better error message. Not sure how to fix yet, but should look into it.
Hi,
I am very happy that this plugin was released just now. I had problems bundling NextJs 13 client components due to the 'use client' before.
Unfortunately I can't decide what should be preserved and what shouldn't. I importing @headlessui/react leads to problems since it uses:
import "client-only";
The following error appears:
[!] (plugin commonjs--resolver) TypeError: Cannot read properties of undefined (reading 'type')
How can we avoid this?
Best
I am facing this issue right now, not sure how to fix it. Here is my rollup.config.js
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import typescript from '@rollup/plugin-typescript';
import terser from '@rollup/plugin-terser';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';
import preserveDirectives from 'rollup-plugin-preserve-directives';
import path from 'path';
import postcss from 'rollup-plugin-postcss';
const packageJson = require('./package.json');
const isProduction = process.env.NODE_ENV === 'production';
const deps = Object.keys(packageJson.dependencies || {});
const projectRootDir = path.resolve(__dirname);
export default [
{
input: 'src/index.ts',
output: [
{
file: packageJson.main,
format: 'cjs',
sourcemap: !isProduction,
preserveModules: true,
},
{
file: packageJson.module,
format: 'esm',
sourcemap: !isProduction,
preserveModules: true,
},
],
watch: {
clearScreen: false,
include: 'src/**',
exclude: [
'node_modules/**',
'dist/**',
'examples/**',
'src/**/*.stories.tsx',
],
},
plugins: [
peerDepsExternal(),
resolve(),
commonjs(),
typescript({
tsconfig: './tsconfig.json',
compilerOptions: {
sourceMap: !isProduction,
inlineSources: !isProduction,
...(!isProduction && { target: 'esnext' }),
},
exclude: ['stories/**/*.@(ts|tsx)'],
}),
isProduction &&
terser({
format: {
comments: /^\s*([@#]__[A-Z]+__\s*$|@cc_on)/,
},
compress: {
directives: false,
},
}),
postcss({
config: {
path: './postcss.config.js',
},
extensions: ['.css'],
minimize: isProduction,
extract: false,
inject: true,
}),
preserveDirectives(),
],
external: (id) => {
const [pkg] = id.split('/');
return deps.includes(pkg);
},
},
];
Hello!
First of all, thank you for your job! This plugin is truly useful in the world of React Server Components and Next App Router :)
I've experienced an issue while using your plugin with Rollup v2.60.0 and wanted to report it to you. I've used it the following way:
import preserveDirectivesPlugin from 'rollup-plugin-preserve-directives';
plugins: [preserveDirectivesPlugin()]
Rollup was throwing the below error:
[!] (plugin preserve-directives) Error: Error running plugin hook renderChunk for preserve-directives, expected a function hook.
I've made some tweaks and ended up with this working:
import preserveDirectivesPlugin from 'rollup-plugin-preserve-directives';
const preserveDirectivesPlugin = preserveDirectives();
plugins: [{ ...preserveDirectivesPlugin, renderChunk: preserveDirectivesPlugin.renderChunk.handler, }]
Cheers!
After updating to Rollup v4, we are starting to get peer dependency warnings.
npm WARN ERESOLVE overriding peer dependency
npm WARN While resolving: redacted
npm WARN Found: [email protected]
npm WARN node_modules/rollup
npm WARN dev rollup@"~4.0.2" from the root project
npm WARN 9 more (@rollup/plugin-commonjs, @rollup/plugin-terser, ...)
npm WARN
npm WARN Could not resolve dependency:
npm WARN peer rollup@"2.x || 3.x" from [email protected]
npm WARN node_modules/rollup-plugin-preserve-directives
npm WARN dev rollup-plugin-preserve-directives@"~0.2.0" from the root project
Cannot bundle using your plugin:
[preserve-directives] Cannot read properties of undefined (reading 'type')
file: vite/modulepreload-polyfill
error during build:
TypeError: Cannot read properties of undefined (reading 'type')
at Object.transform (/Users/oleggulevskyy/Documents/dev/gpt-for-excel/node_modules/rollup-plugin-preserve-directives/dist/index.js:24:84)
at file:///Users/oleggulevskyy/Documents/dev/gpt-for-excel/node_modules/rollup/dist/es/shared/node-entry.js:24395:40
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
Using Vite with React + React query + Rect Intl, where it seems like react-intl
isn't bundling because of this issue you are fixing. However, your plugin fails with this error when I am trying to bundle. Any idea?
Thanks
When trying to import a .css file with the Tailwind @ rules, the following error is thrown:
[!] (plugin preserve-directives) SyntaxError: Unexpected character '@' (1:0)
The module:
"use client";
import "../styles.css";
import styled from "styled-components";
const StyledNextLink = styled.div`
color: red;
`;
export const Test = () => {
return <StyledNextLink>{`Test`}</StyledNextLink>;
};
The CSS file:
@tailwind base;
@tailwind components;
@tailwind utilities;
The rollup.config.js:
import typescript from "@rollup/plugin-typescript";
import postcss from "rollup-plugin-postcss";
import autoprefixer from "autoprefixer";
import tailwindcss from "tailwindcss";
import tailwindConfig from './tailwind.config.js';
import preserveDirectives from 'rollup-plugin-preserve-directives';
import pkg from "./package.json" assert { type: "json" };
export default {
external: [
...Object.keys(pkg.peerDependencies),
...Object.keys(pkg.dependencies || []),
"react/jsx-runtime",
],
input: "src/index.tsx",
output: {
// file: "dist/index.js",
dir: "dist",
preserveModules: true,
format: "cjs",
interop: "auto",
},
watch: {
include: "src/**",
},
plugins: [
preserveDirectives(),
postcss({
extensions: [".css", ".module.css"],
plugins: [autoprefixer(), tailwindcss(tailwindConfig)],
}),
typescript({ include: "src/**/*.{js,ts,jsx,tsx}" }),
],
};
rollup: v2.26.9
rollup-plugin-preserve-directives: v0.4.0
Hi team,
I am trying to use this plugin to preserve 'use client' directive, but when I add this plugin I am getting the below error.
Getting a below error while trying to build esm and cjs:
[esm] [!] (plugin preserve-directives) Error: Error running plugin hook renderChunk for preserve-directives, expected a function hook.
[esm] Error: Error running plugin hook renderChunk for preserve-directives, expected a function hook.
[cjs] [!] (plugin preserve-directives) Error: Error running plugin hook renderChunk for preserve-directives, expected a function hook.
[cjs] Error: Error running plugin hook renderChunk for preserve-directives, expected a function hook.
Hi there,
Thank you for the fantastic plugin. Unfortunately, I have not been able to configure it yet (I need it for react-query). This is what my rollup config currently looks like, how would I configure the plugin?
import typescript from 'rollup-plugin-typescript2';
import dts from 'rollup-plugin-dts';
import commonjs from '@rollup/plugin-commonjs';
import svgr from '@svgr/rollup';
import url from '@rollup/plugin-url';
import json from '@rollup/plugin-json';
import pkg from './package.json';
import sourcemaps from 'rollup-plugin-sourcemaps';
import nodeResolve from '@rollup/plugin-node-resolve';
const config = [
{
input: 'src/index.tsx',
output: [
{
file: pkg.main,
format: 'cjs',
exports: 'named',
},
{
file: pkg.module,
format: 'es',
exports: 'named',
sourcemap: 'inline',
},
],
external: [
'axios',
'react',
'react/jsx-runtime',
'react-number-format',
'collect.js',
'formik',
'yup',
'lodash',
'@date-io/date-fns',
'@mui/material',
'@mui/lab/AdapterDateFns',
'@mui/lab/LocalizationProvider',
'@mui/lab/DatePicker',
'@mui/styles',
'@mui/icons-material',
'@mui/material/styles',
'@mui/styles/makeStyles',
'@mui/x-date-pickers-pro',
'@mui/x-date-pickers-pro/AdapterDateFns',
'react-i18next',
'i18next',
'i18next-browser-languagedetector',
'@mui/icons-material/Delete',
'@mui/icons-material/AddCircleOutlineTwoTone',
'@tanstack/react-query',
'uuid',
],
plugins: [
sourcemaps(),
typescript({
tsconfig: './tsconfig.json',
sourceMap: true,
inlineSources: true,
useTsconfigDeclarationDir: true,
}),
commonjs({
extensions: ['.js', '.ts'],
}),
svgr({ exportType: 'named', jsxRuntime: 'automatic' }),
url({
include: './src/assets/icons/*.svg',
}),
json(),
nodeResolve({
dedupe: [
'useTranslation',
'i18n',
'I18nextProvider',
'@tanstack/react-query',
'useQuery',
'QueryClientProvider',
'axios',
],
}),
/* terser({
compress: {
drop_debugger: false
}
}),*/
],
},
{
input: './build/dts/index.d.ts',
output: [
{
file: 'dist/index.d.ts',
format: 'es',
},
],
plugins: [dts()],
},
];
export default config;
I have tried adding preserveDirectives()
to the plugins, but I get this error: [!] (plugin rpt2) Error: Unexpected token (5:7)
.
I also tried adding preserveDirectives.default()
but I get this error: [!] TypeError: preserveDirectives__default.default.default is not a function
.
How would I add this plugin to my configuration?
Thank you!
I don' think it's a good idea to set output.preserveModules
option to true, ain' there a workaround to this?
my dist directory looks like this
_virtual/
node_modules/
src/
base.js
index.d.ts
index.js
tailwind.config.js
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/rollup
npm ERR! dev rollup@"^4.1.5" from the root project
npm ERR! peerOptional rollup@"^2.68.0||^3.0.0||^4.0.0" from @rollup/[email protected]
npm ERR! node_modules/@rollup/plugin-commonjs
npm ERR! dev @rollup/plugin-commonjs@"^25.0.7" from the root project
npm ERR! 7 more (@rollup/plugin-node-resolve, @rollup/plugin-terser, ...)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer rollup@"2.x || 3.x" from [email protected]
npm ERR! node_modules/rollup-plugin-preserve-directives
npm ERR! dev rollup-plugin-preserve-directives@"^0.2.0" from the root project
I have react components that imports scss files. When adding this plugin I get this error on build:
[preserve-directives] Expression expected
file: --redacted--/packages/buflib/src/components/responsive_image/ResponsiveImage.scss
error during build:
RollupError: Expression expected
at error (file://--redacted--/node_modules/vite/node_modules/rollup/dist/es/shared/parseAst.js:337:30)
at parseError (file://--redacted--/node_modules/vite/node_modules/rollup/dist/es/shared/parseAst.js:972:9)
at convertNode (file://--redacted--/node_modules/vite/node_modules/rollup/dist/es/shared/parseAst.js:2057:12)
at convertProgram (file://--redacted--/node_modules/vite/node_modules/rollup/dist/es/shared/parseAst.js:965:12)
at Object.parseAst [as parse] (file://--redacted--/node_modules/vite/node_modules/rollup/dist/es/shared/parseAst.js:2104:12)
at Object.transform (file://--redacted--/node_modules/rollup-plugin-preserve-directives/dist/index.js:12:26)
at file://--redacted--/node_modules/vite/node_modules/rollup/dist/es/shared/node-entry.js:18692:40
versions:
"vite-plugin-dts": "^3.7.2",
"vite": "^5.0.12"
When running a project as ESM (either by having "type": "module"
in package.json
or using .mjs
extension for Rollup config, see docs for more info), using a default import of this plugin results in an error:
Changing preserveDirectives()
to preserveDirectives.default()
fixes this issue:
// rollup.config.mjs
import preserveDirectives from "rollup-plugin-preserve-directives";
export default {
output: {
preserveModules: true,
},
plugins: [preserveDirectives.default()],
};
I believe this is due to how TypeScript bundles the library code when the esModuleInterop option is set (as is the case in that plugin):
I'm not familiar with how TS compiles the final bundle, but I believe that changing to named exports will fix this issue, and make it work the same in both CommonJS and ESM.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.