Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error: The "fileName" or "name" properties of emitted files must be strings that are neither absolute nor relative paths and do not contain invalid characters #250

Closed
tu4mo opened this issue Mar 9, 2020 · 43 comments · Fixed by #251 or #262

Comments

@tu4mo
Copy link

tu4mo commented Mar 9, 2020

I'm getting an error when I try to define a filename for the extract option.

postcss({
  extract: 'dist/test.css',
  …
})

v2.4.0:

[!] (plugin postcss) Error: The "fileName" or "name" properties of emitted files must be strings that are neither absolute nor relative paths and do not contain invalid characters, received "../test.css".

Works on v2.3.0.

@himself65 himself65 added the bug label Mar 9, 2020
@himself65
Copy link
Collaborator

related ecadc6c

@egoist
Copy link
Owner

egoist commented Mar 10, 2020

🎉 This issue has been resolved in version 2.4.1 🎉

The release is available on:

Your semantic-release bot 📦🚀

@himself65
Copy link
Collaborator

fixed at v2.4.1 via 1170e89

@tu4mo
Copy link
Author

tu4mo commented Apr 18, 2020

@himself65 @SASUKE40 This issue is back in v2.8.1.

@SASUKE40
Copy link
Collaborator

@himself65 @SASUKE40 This issue is back in v2.8.1.

Use v2.6.4 for rollup v1.
v2.8.1 is a beaking change for rollup v2, and it will be deleted soon, and re-tag as v3. It is my fault to use semantic-release in wrong way, that lead to publish a minor verison, sorry!

@tu4mo
Copy link
Author

tu4mo commented Apr 18, 2020

@SASUKE40 I'm using Rollup v2.6.1.

@egoist
Copy link
Owner

egoist commented Apr 19, 2020

🎉 This issue has been resolved in version 2.8.2 🎉

The release is available on:

Your semantic-release bot 📦🚀

@SASUKE40
Copy link
Collaborator

@SASUKE40 I'm using Rollup v2.6.1.

I just released a new version v2.8.2 and hope it solves your problem.

@tu4mo
Copy link
Author

tu4mo commented Apr 19, 2020

I just released a new version v2.8.2 and hope it solves your problem.

Thank you! It almost solved it. Previously I had more control on where the outputted file goes. Now it seems to be created in output.dir, which in my case I have multiple; dist/esm and dist/cjs. Before I could output the CSS file in dist/bundle.css, now it's created in those output folders.

I tried passing extract: '../bundle.css' but that didn't work.

@SASUKE40
Copy link
Collaborator

I just released a new version v2.8.2 and hope it solves your problem.

Thank you! It almost solved it. Previously I had more control on where the outputted file goes. Now it seems to be created in output.dir, which in my case I have multiple; dist/esm and dist/cjs. Before I could output the CSS file in dist/bundle.css, now it's created in those output folders.

I tried passing extract: '../bundle.css' but that didn't work.

I did ignore relative paths like this, let me see how to fix that.

@evdama
Copy link

evdama commented Apr 20, 2020

I tried passing extract: '../bundle.css' but that didn't work.

Same for me with v2.8.2, I'm getting the error with this snippet in my rollup.conf

      postcss({
        plugins: postcssPlugins(!dev),
        extract: path.resolve(__dirname, './static/global.css'),
      } ),

The issue should be re-opened until fixed no?

@SASUKE40
Copy link
Collaborator

image
It is banned from emitFile with relative paths in rollup v2.
I am asking rollup maintainers for help.

@SASUKE40
Copy link
Collaborator

I tried passing extract: '../bundle.css' but that didn't work.

Same for me with v2.8.2, I'm getting the error with this snippet in my rollup.conf

      postcss({
        plugins: postcssPlugins(!dev),
        extract: path.resolve(__dirname, './static/global.css'),
      } ),

The issue should be re-opened until fixed no?

There is no plan to support anything else in the future as e.g. paths leaving the bundle root would violate the assumption that Rollup will only ever modify the target directory.

Related issue: rollup/rollup#3507

@halostatue
Copy link

This comment by @lukastaegert provides the full solution. What I had to do was:

13c05ebd 2020-04-29 | Fix issues with rollup-plugin-postcss (HEAD -> charge-purchase-history) [Austin Ziegler]

diff --git a/assets/rollup.config.js b/assets/rollup.config.js
index 1e976e0f..f1a365a1 100644
--- a/assets/rollup.config.js
+++ b/assets/rollup.config.js
@@ -60,13 +60,14 @@ const plugins = [
 ]
 
 function postcssPlugin(appType) {
-  return postcss({ extract: `${destination}/css/${appType}-app.css`, plugins: [autoprefixer] })
+  return postcss({ extract: `css/${appType}-app.css`, plugins: [autoprefixer] })
 }
 
 const employee = {
   input: 'src/employee-app.js',
   output: {
-    dir: `${destination}/js`,
+    dir: destination,
+    entryFileNames: 'js/[name].js',
     format: 'iife',
     sourcemap: !isProduction ? 'inline' : false,
   },
@@ -76,7 +77,8 @@ const employee = {
 const customer = {
   input: 'src/customer-app.js',
   output: {
-    dir: `${destination}/js`,
+    dir: destination,
+    entryFileNames: 'js/[name].js',
     format: 'iife',
     sourcemap: !isProduction ? 'inline' : false,
   },

This works perfectly.

@evdama
Copy link

evdama commented May 6, 2020

This works perfectly.

Hi @halostatue aka Austin, so I figure you're on v3.1.1 with this patch added or are you still on v2.9.0 like I am because v3.1.1 is broken like mentioned here #264

@SASUKE40 what do you think, is this patch working for v3.1.1 so one could upgrade from v2.9.0?

@SASUKE40
Copy link
Collaborator

SASUKE40 commented May 6, 2020

This works perfectly.

Hi @halostatue aka Austin, so I figure you're on v3.1.1 with this patch added or are you still on v2.9.0 like I am because v3.1.1 is broken like mentioned here #264

@SASUKE40 what do you think, is this patch working for v3.1.1 so one could upgrade from v2.9.0?

The way to generate asset files between rollup v1 and rollup v2 is different.
The plugin uses this.emitFile API and the asset files will be generated based on output.

@halostatue
Copy link

I’m on v3.1.1 and it’s working with the changes I described above.

@evdama
Copy link

evdama commented May 6, 2020

Can't figure it out for some reason, here's my rollup.conf in my Sapper project that works with v2.9 but not v3.1.1

The extract line is line 186 in the server section extract: 'static/global.css',

import { terser } from 'rollup-plugin-terser'
import babel from 'rollup-plugin-babel'
import commonjs from 'rollup-plugin-commonjs'
import config from 'sapper/config/rollup.js'
import environmentVariables from './config/env'
import getPreprocessor from 'svelte-preprocess'
import getTime from 'date-fns/getTime'
import json from '@rollup/plugin-json'
import pkg from './package.json'
import postcss from 'rollup-plugin-postcss'
import replace from '@rollup/plugin-replace'
import resolve from 'rollup-plugin-node-resolve'
import svelte from 'rollup-plugin-svelte'
import visualizer from 'rollup-plugin-visualizer'


const mode = process.env.NODE_ENV
const dev = mode === 'development'
const legacy = !!process.env.SAPPER_LEGACY_BUILD

const onwarn = ( warning, onwarn ) => ( warning.code === 'CIRCULAR_DEPENDENCY' && /[/\\]@sapper[/\\]/.test( warning.message ) ) || onwarn( warning )

const dedupe = importee => importee === 'svelte' || importee.startsWith( 'svelte/' )

const appConfig = Object.keys(environmentVariables).reduce((acc, n) => {
  acc[`${n}`] = environmentVariables[n]
  return acc
}, {})


  const svelteExtractor = ( content ) => {
    const regExp = new RegExp(/[A-Za-z0-9-_:/]+/g)
    const matchedTokens = []
    let match = regExp.exec(content)

    while (match) {
      if (match[0].startsWith('class:')) {
        matchedTokens.push(match[0].substring(6))
      } else {
        matchedTokens.push(match[0])
      }
      match = regExp.exec(content)
    }
    return matchedTokens
  }


const postcssPlugins = ( purgecss = false ) =>
  [
    require('postcss-import')(),
    require('postcss-url')(),
    require('tailwindcss')({ config: 'tailwind.config.js' }),
    require('autoprefixer')({
      overrideBrowserslist: 'last 1 version',
    }),
    // Do not purge the CSS in dev mode to be able to play with classes in the browser dev-tools.
    purgecss &&
      require('@fullhuman/postcss-purgecss')({
        content: [
          'src/**/*.html',
          'src/**/*.svelte',
          'src/**/*.css',
          'static/**/*.css',
        ],
        extractors: [
          {
            extractor: svelteExtractor,

            // Specify the file extensions to include when scanning for class names.
            extensions: [ 'svelte', 'css', 'html' ],
          },
        ],
        fontFace: true,
        // Whitelist selectors to stop Purgecss from removing them from your CSS.
        whitelist: [ 'html', 'body' ],
        whitelistPatterns: [/svelte-/]
      }),
    purgecss &&
      require('cssnano')({
        preset: 'default',
      }),
  ].filter(Boolean)

const preprocess = getPreprocessor({
  transformers: {
    postcss: {
      plugins: postcssPlugins(), // Don't need purgecss because Svelte handles unused css for you.
    },
  },
})



export default {
  client: {
    input: config.client.input(),
    output: config.client.output(),
    plugins: [
      // eslint(),
      visualizer( { filename: 'visualizer_stats/client.json', title: 'Client Bundle', json: true } ),
      replace({
        'process.browser': true,
        'process.env.NODE_ENV': JSON.stringify( mode ),
        ROLLUP_DEV_OR_PROD_URL: ( dev ? '.': appConfig.EDM_URL ),
        ROLLUP_EDM_UPDATE_TIMESTAMP: getTime( new Date() ),
        ROLLUP_GOLIVE_DATE: appConfig.GOLIVE_DATE,
        ROLLUP_RECAPTCHA_SITE_KEY: appConfig.RECAPTCHA_SITE_KEY,
      }),
      svelte({
        dev,
        hydratable: true,
        emitCss: false,
        preprocess,
      }),
      resolve({
        browser: true,
        dedupe,
      }),
      commonjs(),
      legacy &&
        babel({
          extensions: ['.js', '.mjs', '.html', '.svelte'],
          runtimeHelpers: true,
          exclude: ['node_modules/@babel/**'],
          presets: [
            [
              '@babel/preset-env',
              {
                targets: '> 0.25%, not dead',
              },
            ],
          ],
          plugins: [
            '@babel/plugin-syntax-dynamic-import',
            [
              '@babel/plugin-transform-runtime',
              {
                useESModules: true,
              },
            ],
          ],
        }),
      !dev &&
        terser({
          module: true,
        }),
    ],
    onwarn,
  },

  server: {
    input: config.server.input(),
    output: config.server.output(),
    plugins: [
      // eslint(),
      visualizer( { filename: 'visualizer_stats/server.json', title: 'Server Bundle', json: true } ),
      replace({
        'process.browser': false,
        'process.env.NODE_ENV': JSON.stringify( mode ),
        ROLLUP_DEV_OR_PROD_URL: ( dev ? '.': appConfig.EDM_URL ),
        ROLLUP_EDM_UPDATE_TIMESTAMP: getTime( new Date() ),
        ROLLUP_EXPRESS_SESSION_COOKIE_SIGNING_SECRET: appConfig.EXPRESS_SESSION_COOKIE_SIGNING_SECRET,
        ROLLUP_IPREGISTRY_KEY: appConfig.IPREGISTRY_KEY,
        ROLLUP_IPREGISTRY_URL: appConfig.IPREGISTRY_URL,
        ROLLUP_RECAPTCHA_SCORE_IS_BOT: appConfig.RECAPTCHA_SCORE_IS_BOT,
        ROLLUP_RECAPTCHA_SCORE_IS_HUMAN: appConfig.RECAPTCHA_SCORE_IS_HUMAN,
        ROLLUP_RECAPTCHA_SECRET_KEY: appConfig.RECAPTCHA_SECRET_KEY,
        ROLLUP_RECAPTCHA_VERIFY_URL: appConfig.RECAPTCHA_VERIFY_URL,
      }),
      svelte({
        generate: 'ssr',
        dev,
        preprocess,
      }),
      resolve({
        dedupe,
      }),
      commonjs(),
      postcss({
        plugins: postcssPlugins(!dev),
        extract: 'static/global.css',
      }),
      json()
    ],
    external: Object.keys(pkg.dependencies).concat(
      require('module').builtinModules ||
        Object.keys(process.binding('natives'))
    ),
    onwarn,
  },

  serviceworker: {
    input: config.serviceworker.input(),
    output: config.serviceworker.output(),
    plugins: [
      // eslint(),
      visualizer( { filename: 'visualizer_stats/service-worker.json', title: 'Service Worker Bundle', json: true } ),
      resolve(),
      replace({
        'process.browser': true,
        'process.env.NODE_ENV': JSON.stringify( mode || 'production'),
      }),
      commonjs(),
      !dev && terser(),
    ],
    onwarn,
  }
}

I'd be very greatful if somebody could maybe spot an obvious mistake I'm making for it not to work with v3.1.1.

@jhoffmcd
Copy link

jhoffmcd commented May 6, 2020

Still getting this with version 3.1.1. It is not clear from this thread what the solution (other than rolling back to version 2.9.0) should be for users on version 3.1.1. Perhaps a new issue would be in order?

@halostatue
Copy link

The changes I put in my comment resolved this perfectly for me. I’m doing this by exporting an array of configurations (export [customer, employee]), though—not with an object of configurations.

@evdama, your comment I can’t quite figure out what the output of your config.{client,server,serviceworker}.output() values would be. What I found is that I had to
return both dir and entryFileNames keys for this to work. (My output dir is ../priv/static/ resulting in ../priv/static/js/customer-app.js and ../priv/static/css/customer-app.css.)

@jhoffmcd
Copy link

jhoffmcd commented May 7, 2020

@halostatue Ah I see what you did, I was looking at @evdama example because they are working in the same system as me (Sapper.js). I will mess around a bit more with the configuration and see if I can get it to work within the build configuration that works for Sapper.js

@evdama
Copy link

evdama commented May 7, 2020

@evdama, your comment I can’t quite figure out what the output of your config.{client,server,serviceworker}.output() values would be.

Hi @jhoffmcd, Hi @halostatue and thanks for asking, my output() in the Sapper project is a bunch of function which are part of the Sapper project.

They are imported into the above rollup.conf with import config from 'sapper/config/rollup.js'.

Below is the file with the output() functions as they get imported into the rollup.conf:

'use strict';

var __chunk_3 = require('./chunk3.js');

const sourcemap = __chunk_3.dev ? 'inline' : false;

var rollup = {
	dev: __chunk_3.dev,

	client: {
		input: () => {
			return `${__chunk_3.src}/client.js`
		},

		output: () => {
			let dir = `${__chunk_3.dest}/client`;
			if (process.env.SAPPER_LEGACY_BUILD) dir += `/legacy`;

			return {
				dir,
				entryFileNames: '[name].[hash].js',
				chunkFileNames: '[name].[hash].js',
				format: 'esm',
				sourcemap
			};
		}
	},

	server: {
		input: () => {
			return {
				server: `${__chunk_3.src}/server.js`
			};
		},

		output: () => {
			return {
				dir: `${__chunk_3.dest}/server`,
				format: 'cjs',
				sourcemap
			};
		}
	},

	serviceworker: {
		input: () => {
			return `${__chunk_3.src}/service-worker.js`;
		},

		output: () => {
			return {
				file: `${__chunk_3.dest}/service-worker.js`,
				format: 'iife',
				sourcemap
			}
		}
	}
};

module.exports = rollup;
//# sourceMappingURL=rollup.js.map

@halostatue
Copy link

I don’t use Sapper, so I can’t really answer on this one. Based on what I see, the CSS directory will be:

`${__chunk_3.dest}/client/static/global.css`

@ghost
Copy link

ghost commented May 7, 2020

Hi @evdama that's now separated and this template is now using svelte-preprocess instead of compiling postcss with rollup-plugin-postcss. Take a look at https://github.com/nhristov/sapper-template-rollup/blob/master/rollup.config.js.

@jhoffmcd
Copy link

jhoffmcd commented May 7, 2020

@nhristov @evdama awesome, just changed my setup to look more like the updated rollup Sapper template. This is much better DX in my opinion than fighting with bundler config. Confirmed everything working as expected.

@evdama
Copy link

evdama commented May 7, 2020

@evdama
Copy link

evdama commented May 8, 2020

Still getting this with version 3.1.1. It is not clear from this thread what the solution (other than rolling back to version 2.9.0) should be for users on version 3.1.1. Perhaps a new issue would be in order?

Or reopen this one because I'd agree, there's no solution yet as far as I can tell...

@coxmi
Copy link
Contributor

coxmi commented May 8, 2020

@evdama @jhoffmcd

Unless I've misunderstood what you need, the quick fix is to use a path like static/output.css in the extract option, rather than ./static/output.css (with a .). It’s resolved relative to the output.dir set in the main rollup config.

If you want to use a relative path (e.g. outside of the output.dir), that's not officially supported by the rollup emitFile API, which this plugin uses. When I was playing around directly with emitFile API though, I did have success using a file path like notarealfolder/../../outsideOfOutputDir.file.

I've not tried this for rollup-plugin-postcss, but if that suits your use case, it might be worth giving it a go.

@evdama
Copy link

evdama commented May 11, 2020

@jhoffmcd I tried https://www.apostrof.co/blog/getting-tailwind-css-to-integrate-nicely-with-svelte-sapper/ which didn't work for me because bundle build times went up to about 3-5 Minutes and even then some custom tailwind classes were missing from the bundle.

@MichaelAnd You're right, and I've already done so as you can see from the extract line ( extract: 'static/global.css',) in my rollup config above.

@halostatue yes, you're right with ${__chunk_3.dest}/client/static/global.css but then my extract line is part of the server section, not the client section.

Still, the issue remains, my setup as can be seen above from the rollup.conf and the Sapper config works with rollup-plugin-postcss v2.9.0 but not with v3.1.1. With v3.1.1 static/global.css isn't written/produced, with v2.9.0 it's written and all is good as I can reference it in my template.html. Maybe @egoist or @SASUKE40 have an idea what to do?

@evdama
Copy link

evdama commented May 20, 2020

fixed my issue: extract: 'global.css' and then move global.css to the static directory during npm build because with Sapper the bundle root is the __sapper__ directory.

@RobbieTheWagner
Copy link

@evdama good suggestion, although I am not sure why there is no way to specify the path in this plugin.

I had to do similar hacks of:

"postbuild": "rimraf ./dist/css && mkdir ./dist/css && mv ./dist/js/shepherd.css ./dist/css/shepherd.css",

@RobbieTheWagner
Copy link

Another thing that works to copy to the correct path is using rollup-plugin-copy:

       postcss({
          plugins: [
            require('autoprefixer'),
            require('cssnano')
          ],
          extract: 'dist/css/shepherd.css'
        }),
        copy({
          targets: [
            { src: 'dist/js/dist/css/*', dest: 'dist/css' }
          ]
        }),

@evdama
Copy link

evdama commented May 25, 2020

@rwwagner90 do you know how to move rather than copy a file with rollup-plugin-copy?
I don't need the global.css twice after I copy it for example. Also, how do you copy a file to outside the bundle root with it?

For deleting all I found so far was https://github.com/vladshcherbin/rollup-plugin-delete

@evdama
Copy link

evdama commented May 25, 2020

didn't work outside the bundle root so I ended up using one predeploy script

const fs = require('fs-extra');

fs.remove('./functions/__sapper__').then(() => {
  fs.moveSync('./__sapper__/build/server/global.css', './static/global.css');  // <-- here is where I do the move now
  fs.copySync('./__sapper__', './functions/__sapper__');
});

@RobbieTheWagner
Copy link

@evdama this was all I needed to copy to the path I wanted:

     copy({
          targets: [
            { src: 'dist/js/dist/css/*', dest: 'dist/css' }
          ]
        }),

It moved it from the incorrect path nested under the js bundle root, to the correct path of dist/css.

As for removing the extra file, I was just using rimraf to remove the leftovers.

@andriusign
Copy link

I have just tried 4.0.2 which is the latest version at the moment and it is still broken. Any plans to fix this issue?

@entenity
Copy link

It has not been fix this issue for 100 years

@mrfzd
Copy link

mrfzd commented Apr 23, 2022

I came here with the hope of seeing this being fixed, and yet after 2 years still not fixed, unbelievable!!!

Here is my config and yet didn't work;

image

As per the config above, added the "dist" directory with the hope of producing a single stylesheet for both ESM and CJS but not lucky, instead, both ESM and CJS ended up with their own stylehseet.css but in a nested folder, the "dist", like so;

image

This is absolutely shocking!

@leonimurilo
Copy link

I came here with the hope of seeing this being fixed, and yet after 2 years still not fixed, unbelievable!!!

Here is my config and yet didn't work;

image

As per the config above, added the "dist" directory with the hope of producing a single stylesheet for both ESM and CJS but not lucky, instead, both ESM and CJS ended up with their own stylehseet.css but in a nested folder, the "dist", like so;

image

This is absolutely shocking!

I share the same

@leonimurilo
Copy link

I've done this workaround using rollup-plugin-copy and rollup-plugin-delete

export default [
  {
    input: 'src/index.ts',
    output: [
      {
        file: packageJson.main,
        format: 'cjs',
        sourcemap: true,
      },
      {
        file: packageJson.module,
        format: 'esm',
        sourcemap: true,
      },
    ],
    plugins: [
      peerDepsExternal({
        includeDependencies: true,
      }),
      resolve(),
      commonjs(),
      typescript({ tsconfig: './tsconfig.json' }),
      postcss({
        extract: true,
        modules: true,
        minimize: true,
      }),
      terser(),
      visualizer(),
    ],
  },
  {
    input: 'dist/esm/types/index.d.ts',
    output: [{ file: 'dist/index.d.ts', format: 'esm' }],
    plugins: [
      copy({
        targets: [{ src: 'dist/cjs/index.css', dest: 'dist/styles' }],
        verbose: true,
        hook: 'buildStart',
      }),
      del({
        targets: ['dist/cjs/index.css', 'dist/esm/index.css'],
        verbose: true,
        hook: 'buildEnd',
      }),
      dts(),
    ],
    external: [/\.(css|less|scss)$/],
    watch: false,
  },
];

@felixcatto
Copy link

felixcatto commented Mar 25, 2023

For me this works perfectly and you don't need to copy / delete anything - #250 (comment)
I also used same hack in webpack, seems it will be cool to add it to readme.

@eendkonijn
Copy link

I had the same error on version 4.0.2. What worked for me was using path.resolve:

postcss({ extract: path.resolve('packages/the-one/dist/modules.css'), modules: true, }),

As it says in the docs https://github.com/egoist/rollup-plugin-postcss

@DarkFalling
Copy link

I had the same error on version 4.0.2. What worked for me was using path.resolve:

postcss({ extract: path.resolve('packages/the-one/dist/modules.css'), modules: true, }),

As it says in the docs https://github.com/egoist/rollup-plugin-postcss

Not work for me if I use output.file other than output.dir

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment