GithubHelp home page GithubHelp logo

sapphi-red / vite-plugin-static-copy Goto Github PK

View Code? Open in Web Editor NEW
230.0 2.0 26.0 424 KB

rollup-plugin-copy with dev server support.

License: MIT License

JavaScript 2.25% TypeScript 97.75%
vite vite-plugin

vite-plugin-static-copy's Introduction

vite-plugin-static-copy

npm version CI MIT License

rollup-plugin-copy for Vite with dev server support.

Note

Before you use this plugin, consider using public directory or import in JavaScript. In most cases, these will work.

Install

npm i -D vite-plugin-static-copy # yarn add -D vite-plugin-static-copy

Usage

Add viteStaticCopy plugin to vite.config.js / vite.config.ts.

// vite.config.js / vite.config.ts
import { viteStaticCopy } from 'vite-plugin-static-copy'

export default {
  plugins: [
    viteStaticCopy({
      targets: [
        {
          src: 'bin/example.wasm',
          dest: 'wasm-files'
        }
      ]
    })
  ]
}

For example, if you use the config above, you will be able to fetch bin/example.wasm with fetch('/wasm-files/example.wasm'). So the file will be copied to dist/wasm-files/example.wasm.

Warning

If you are using Windows, make sure to use normalizePath after doing path.resolve or else. \ is a escape charactor in fast-glob and you should use /.

import { normalizePath } from 'vite'
import path from 'node:path'

normalizePath(path.resolve(__dirname, './foo')) // C:/project/foo

// instead of
path.resolve(__dirname, './foo') // C:\project\foo

See fast-glob documentation about this for more details.

Options

See options.ts.

Differences with rollup-plugin-copy

  • Faster dev server start-up than using rollup-plugin-copy on buildStart hook.
    • Files are not copied and served directly from the server during dev to reduce start-up time.
  • dest is relative to build.outDir.
    • If you are going to copy files outside build.outDir, you could use rollup-plugin-copy instead. Because that does not require dev server support.
  • fast-glob is used instead of globby.
    • Because fast-glob is used inside vite.
  • transform could return null as a way to tell the plugin not to copy the file, this is similar to the CopyWebpackPlugin#filter option, but it expects transform to return the original content in case you want it to be copied.
  • transform can optionally be an object, with a handler property (with the same signature of the rollup-plugin-copy transform option) and an encoding property (BufferEncoding | 'buffer') that will be used to read the file content so that the handler's content argument will reflect the correct encoding (could be Buffer);
  • structured: true preserves the directory structure. This is similar to flatten: false in rollup-plugin-copy, but it covers more edge cases.

vite-plugin-static-copy's People

Contributors

a982246809 avatar antfu avatar brunoimbrizi avatar d3mi3n avatar dependabot[bot] avatar fezvrasta avatar github-actions[bot] avatar jaluik avatar jisay avatar oliversalzburg avatar sapphi-red avatar seliverstov-logema avatar vilicvane avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

vite-plugin-static-copy's Issues

[Help] Clarification of usage behaviour

I am using electron-vite package boilerplate and I need to find a way to add python as child process. There is an issue in getting some files copied over to the "dist" folder and in [PR#225] (electron-vite/electron-vite-vue#255), this plugin is recommended.

The following is my setup:
image

How do I make sure a py folder is copied over to the dist folder ya? Both during dev and build.

Runs before certain build folders are available

I have a nuxt3 project and I want to copy a static file into the .output/server/ folder.

It seems the copy plugin runs before the build is complete:
image

Here is a video the plugin copying the file (orders.json) and then it gets removed as the build progresses:

vite-plugin-copy.mp4

Is there any way around this?

// https://nuxt.com/docs/api/configuration/nuxt-config
import { viteStaticCopy } from 'vite-plugin-static-copy'
import { normalizePath } from 'vite'
import path from 'node:path'

export default defineNuxtConfig({
  pages: true,
  modules: ["nuxt-windicss"],
  vite: {
    plugins: [
      viteStaticCopy({
        targets: [
          {
            src: normalizePath(path.resolve(__dirname, 'data/orders.json')),
            dest: path.resolve(__dirname, '.output')
          }
        ]
      })
    ] 
  }
})

files are copied to the `public` folder but not to the `build` one

I didn't notice this before because I did run the build a couple of times before so the files were already in the public folder, but I just realized that if I remove them from public and I run vite build the files end up being copied to public but not in the final build folder.

Are you aware of any reason of why this could happen?

"vite-plugin-static-copy" resolved to an ESM file

I'm doing something like this in my vite config:

import { viteStaticCopy } from 'vite-plugin-static-copy';

export default defineConfig({
  plugins: [
    solidPlugin(),
    viteStaticCopy({
      targets: [
         {
           src: resolvePath('/assets'),
           dest: resolvePath('dist')
         }
      ]

But receiving the error:

"vite-plugin-static-copy" resolved to an ESM file. ESM file cannot be loaded by `require`. 
See https://vitejs.dev/guide/troubleshooting.html#this-package-is-esm-only for more details. [plugin externalize-deps]

This is confusing because I'm importing viteStaticCopy.

binary files are corrupted when copied

I need to copy some .wasm files but when this plugin copies them they get corrupted (diff build/file.wasm statics/file.wasm reports they differ).

I'm using the transform option to filter some of them out.
I see the plugin reads the files as utf-8, shouldn't it preserve the original encoding?

Is this a known issue? Any workaround?

Unable to access assets from public dir

Apologies if i've missed something obvious, but I'm having issues serving a JSON file from the public dir while running the dev server.

I understand that the files are not physically copied when running the dev server, but my assumption is that they are still accessible.

viteStaticCopy({
  targets: [
    {
      src: '../../libs/my-lib/translations/en-US/translations.json',
      dest: './'
    }
  ]
})

Trying to access the file (via browser) on: http://localhost:8080/translations.json and getting a 404.

I've tried multiple different values for dest including:

  • ./
  • /
  • public
  • /public
  • ./public
  • apps/my-app/public
  • /apps/my-app/public
  • etc.

Nothing seems to work.

I can see that it is finding the file in question:
[vite-plugin-static-copy] Collected 1 items.

Am I missing something? Thanks in advance!

how to rename file?

I want to rename the file from web.mode.config to web.config:

const build = ({ mode }) =>
  defineConfig({
    base: "/sightline",
    server: {
      port: 3000,
    },
    plugins: [
      react(),
      viteStaticCopy({
        targets: [
          {
            src: `src/web.${mode}.config`,
            dest: "./",
          },
        ],
      }),
    ],
  });

However, this is creating a file web.staging.config in the public directory.

Posibility to only use for serve or build mode

Hey @sapphi-red, thanks for this amazing vite-plugin.

I need to use the plugin only for serve mode. I've already tried the following with no luck

plugins: [ { ...viteStaticCopy({ targets: [ { src: __dirname + '/../httpdocs/css', dest: 'css' } ] }), apply: 'serve' }, vue(), ],

Do you know how I can achieve this? Thanks!

watcher: Cannot read properties of undefined (reading 'close')

Hello, I newly installed this plugin and see TypeError: Cannot read properties of undefined (reading 'close') when I started copying.

The copy does work correctly, it's just at the end that it throws this error

Error details below

TypeError: Cannot read properties of undefined (reading 'close')
at Object.closeBundle (/home/quentin/MEGAsync/JavaScript//node_modules/vite-plugin-static-copy/dist/index.cjs:1070:21)
at file:///home/quentin/MEGAsync/JavaScript//node_modules/rollup/dist/es/shared/node-entry.js:25544:40
at async Promise.all (index 0)
at async PluginDriver.hookParallel (file:///home/quentin/MEGAsync/JavaScript//node_modules/rollup/dist/es/shared/node-entry.js:25472:9)
at async Object.close (file:///home/quentin/MEGAsync/JavaScript//node_modules/rollup/dist/es/shared/node-entry.js:26726:13)
at async build (file:///home/quentin/MEGAsync/JavaScript//node_modules/vite/dist/node/chunks/dep-df561101.js:48021:13)
at async CAC. (file:///home/quentin/MEGAsync/JavaScript//node_modules/vite/dist/node/cli.js:822:9)

It is caused by

async closeBundle() {
  await watcher.close();
}

My dependencies

"devDependencies": {
    "vite": "^4.4.9",
    "vite-plugin-static-copy": "^0.17.0"
}

Errors resolving assets from multiple targets

The plugin crashes vite in dev mode when it doesn't find the requested asset in the first target.

        "vite": "2.9.9",
        "vite-plugin-pwa": "0.12.0",
        "vite-plugin-static-copy": "0.5.0",
        "vite-raw-plugin": "1.0.1",

The requested asset exists in the second target.

viteStaticCopy({
    targets: [
        { src: path.resolve(__dirname, 'node_modules/@myorg/test-library/src/assets/*'), dest: '.' },
        { src: 'src/assets/*', dest: '.' }
    ]
}),

// or 

viteStaticCopy({
    targets: [
        { src: [ path.resolve(__dirname, 'node_modules/@myorg/test-library/src/assets/*'), 
                 path.resolve(__dirname, 'src/assets/*') ],
          dest: '.'
        }
    ]
}),

In dev mode, vite process will crash when the asset from the second target is requested:

node:fs:1536
  handleErrorFromBinding(ctx);
  ^

Error: ENOENT: no such file or directory, stat '/Users/test/myproject/node_modules/@myorg/test-library/src/assets/test-icon.svg'
    at statSync (node:fs:1536:3)
    at sendStatic (/Users/test/myproject/node_modules/vite-plugin-static-copy/dist/index.cjs:665:45)
    at viteServeStaticCopyMiddleware (/Users/test/myproject/node_modules/vite-plugin-static-copy/dist/index.cjs:741:5)
    at call (/Users/test/myproject/node_modules/vite/dist/node/chunks/dep-59dc6e00.js:43823:7)
    at next (/Users/test/myproject/node_modules/vite/dist/node/chunks/dep-59dc6e00.js:43767:5)
    at Function.handle (/Users/test/myproject/node_modules/vite/dist/node/chunks/dep-59dc6e00.js:43770:3)
    at Server.app (/Users/test/myproject/node_modules/vite/dist/node/chunks/dep-59dc6e00.js:43635:37)
    at Server.emit (node:events:390:28)
    at parserOnIncoming (node:_http_server:951:12)
    at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17) {
  errno: -2,
  syscall: 'stat',
  code: 'ENOENT',
  path: '/Users/test/myproject/node_modules/@myorg/test-library/src/assets/test-icon.svg'
}

Both targets have the same folder structure that we want to merge assets from when we build. The production build fails with this setup with the file already exists error. The current workaround is to use the rollup-plugin-copy but that lacks support for virtual static assets for dev-mode without copying them to project root.

[vite-plugin-static-copy:build] EEXIST: file already exists, mkdir '/Users/test/project/dist/images'
[vite-plugin-static-copy] Copy count was not set.

error during build:
Error: EEXIST: file already exists, mkdir '/Users/test/project/dist/images'
node:child_process:903
    throw err;
    ^

Error: Command failed: vite build --mode production
    at checkExecSyncError (node:child_process:826:11)
    at Object.execSync (node:child_process:900:15)
    at buildApp (/Users/test/project/build/build.js:7:11)
    at Object.<anonymous> (/Users/test/project/build/build.js:10:1)
    at Module._compile (node:internal/modules/cjs/loader:1095:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1147:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47 {
  status: 1,
  signal: null,
  output: [ null, null, null ],
  pid: 15469,
  stdout: null,
  stderr: null
}

For reference, the first @myorg/test-library is a private internal library that contains some common assets and components used by the parent myproject.

How to copy wasm files for vite-plugin-comlink

Hey,

I am using comlink plugin to load workers and the workers inturn load .wasm files

In my vite plugins config, I have: (solution from https://stackoverflow.com/a/75616365/23147840)

 plugins: [
            viteStaticCopy({
                targets: [
                    {
                        src: "public/wasm/mozjpeg_wasm.wasm",
                        dest: "src/internals/services/image-service/mozjpeg/internal\:comlink\:./",
                    },
                ]
            }),
  1. This works fine in dev server
  2. Fails when I make build
16:49:45 [ERROR] [vite] [vite-plugin-static-copy:build] Path contains invalid characters: C:\Projects\dist\src\internals\services\image-service\mozjpeg\internal:comlink:.
Path contains invalid characters: C:\Projects\dist\src\internals\services\image-service\mozjpeg\internal:comlink:.
  Stack trace:
    at checkPath (C:\Projects\node_modules\fs-extra\lib\mkdirs\utils.js:16:21)
    at C:\Projects\node_modules\universalify\index.js:18:45
    at async copyAll (file:///C:/Projects/node_modules/vite-plugin-static-copy/dist/index.js:563:7)
    at async Promise.all (index 1)
    at async file:///C:/Projects/node_modules/rollup/dist/es/shared/node-entry.js:19526:13

any help is appreciated.

[Vite 3] when you run Vite dev doesn't copy the files

Hello, I've seen #10, and it's not working. I have this configuration:

vite.config.js

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue2';
import EnvironmentPlugin from 'vite-plugin-environment';
import { viteStaticCopy } from 'vite-plugin-static-copy';

import { normalizePath } from 'vite';
import path from 'node:path';

export default defineConfig({
	plugins: [
		laravel({
			input: ['resources/js/app.js'],
			refresh: true
		}),
		vue({
			template: {
				transformAssetUrls: {
					base: null,
					includeAbsolute: false
				}
			}
		}),
		EnvironmentPlugin('all'),
		viteStaticCopy({
			targets: [
				{
					src: normalizePath(path.resolve(__dirname, './resources/images')),
					dest: normalizePath(path.resolve(__dirname, './public'))
				}
			]
		})
	],
	resolve: {
		alias: {
			'@': '/resources/js',
			'@images': '/resources/images'
		}
	},
	css: {
		preprocessorOptions: {
			scss: {
				additionalData: `@import "/resources/sass/_variables.scss";`
			}
		}
	}
});

package.json

{
  "scripts": {
        "dev": "vite serve",
        "build": "vite build"
  },
  "devDependencies": {
       "vite-plugin-static-copy": "^0.7.0",
       "vite": "^3.0.4",
  }
}

destDir resolving to root and ../ not supported

I bumped into a small bug and an unsupported case when using flatten: false

The small bug: destDir resolves to the root folder when dest is empty (utils.ts line 66)

This example results in the contents of /locales copied to C:/ (assuming Windows):

viteStaticCopy({ targets: [ { src: 'locales/**/*.json', dest: '' } ], flatten: false })

The unsupported case: parent folders ../ as sources

This example works as expected and copies /locales to the destination:

viteStaticCopy({ targets: [ { src: '../../static/locales', dest: '' } ] })

This example copies /static to the destination (which is C:/ on Windows, as mentioned above):

viteStaticCopy({ targets: [ { src: '../../static/locales/**/*.json', dest: '' } ], flatten: false })

Add optional src watcher

Hey... many thanks for this awesome plugin. What's the best way to add file or dir watcher for any changes in the src dir?

Error message while/after files copied

I need to copy some assets from one package in my npm workspace directory to other packages in workspace.

I use the following vite config to build my library.

import { resolve } from 'path'

import { viteStaticCopy } from 'vite-plugin-static-copy'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [
    viteStaticCopy({
      targets: [
        {
          src: './public/shared',
          dest: './../../app/public',
        },
      ],
    }),
    vue(),
  ] as any[],
  build: {
    lib: {
      entry: resolve(__dirname, 'src/lib.ts'),
      name: 'Name',
      fileName: 'index',
    },
    rollupOptions: {
      external: ['vue'],
      output: {
        globals: {
          vue: 'Vue',
        },
      },
    },
  },
})

Then if I watch (or build) the library, I get this error (but the files are copied correctly)

> vue-tsc && vite build --watch

vite v5.0.1 building for production...

watching for file changes...

build started...
✓ 6 modules transformed.
dist/index.umd.cjs  0.88 kB │ gzip: 0.57 kB
dist/style.css  8.86 kB │ gzip: 2.01 kB
dist/index.js   0.85 kB │ gzip: 0.52 kB
[vite-plugin-static-copy:build] ENOENT: no such file or directory, unlink '/packages/app/public/shared/fonts/Inter-Bold.woff2'
[vite-plugin-static-copy] Copied 1 items.

Latest version seems to break vite build

Got the following when using v1.0.0

Error:` Build failed with 1 error:
node_modules/esbuild/lib/main.js:1373:27: ERROR: [plugin: externalize-deps] "vite-plugin-static-copy" resolved to an ESM file. 

ESM file cannot be loaded by `require`. See https://vitejs.dev/guide/troubleshooting.html#this-package-is-esm-only for more details.

Downgrading to v.0.17.1 fixes the issue

Error during initial build

I am getting an error during the initial build after install.

plugins: [
  viteStaticCopy({
    targets: [
      {
        src: './node_modules/PACKAGE/src/fonts/',
        dest: './public/fonts/'
      },
      {
        src: './node_modules/PACKAGE/src/img/',
        dest: './public/img/'
      }
    ]
  }),
  vue()
]

vite build

failed to load config from C:\XYZ\DEV\training\vite.config.js
error during build:
C:\XYZ\DEV\training\node_modules\vite-plugin-static-copy\dist\index.js:32
import * as qs from "querystring";
^

SyntaxError: Unexpected token *
at Module._compile (internal/modules/cjs/loader.js:811:22)
at Module._extensions..js (internal/modules/cjs/loader.js:879:10)
at Object.require.extensions. [as .js] (C:\XYZ\DEV\training\node_modules\vite\dist\node\chunks\dep-f5552faa.js:75173:13)
at Module.load (internal/modules/cjs/loader.js:731:32)
at Function.Module._load (internal/modules/cjs/loader.js:644:12)
at Module.require (internal/modules/cjs/loader.js:771:19)
at require (internal/modules/cjs/helpers.js:68:18)
at Object. (C:\XYZ\DEV\training\vite.config.js:30:49)
at Module._compile (internal/modules/cjs/loader.js:868:30)
at Object.require.extensions. [as .js] (C:\XYZ\DEV\training\node_modules\vite\dist\node\chunks\dep-f5552faa.js:75170:20)
npm ERR! code ELIFECYCLE

A great tool but

A great tool but, if encrypting the file after making copies of it

src => js/name.js
dist => js/name~12c54c.js

Thanks :)

Support for optional file watching

Hi there! I recently integrated the plugin in my project and it perfectly fit my needs. However, I ran into an issue with file watching in CI/CD - with chokadir running it hits the limit of fs watchers. Given that file watching in CI/CD is not required, maybe it would be a good idea to make file watching optional?

The 1.0.1 version `rename` update

I noticed that with the latest update the rename function gets the fullPath, the third argument, as an absolute system path now, as opposed to the project relative path.
So /Users/username/long/path/to/project/folder/file/path instead of folder/file/path;

Should there be a way to control this?
It's kind of a breaking change.

The entire module stopped working

I made this update progress:
Bump vite-plugin-static-copy from 0.17.1 to 1.0.0

"@vitejs/plugin-react": "4.2.1",
"vite": "5.0.7",
"vite-plugin-electron": "^0.15.4",
"vite-plugin-electron-renderer": "^0.14.5",
"vite-plugin-static-copy": "1.0.0"

Now the module no longer loads on Vite in any way.

vite.config.js:4:31:
      4 │ import { viteStaticCopy } from 'vite-plugin-static-copy';

Error: Build failed with 1 error:
node_modules/esbuild/lib/main.js:1373:27: ERROR: [plugin: externalize-deps] "vite-plugin-static-copy" resolved to an ESM file. ESM file cannot be loaded by `require`. See https://vitejs.dev/guide/troubleshooting.html#this-package-is-esm-only for more details.

When I downgraded, everything went back to normal. So the problem is in the version 1.0.0

[Windows] EPERM: operation not permitted, symlink

OS: Windows 11

In dev mode, it works perfectly, but when I try to build, the following error exists:

Error: EPERM: operation not permitted, symlink 'D:\Solutions\my-repo\node_modules\.pnpm\[email protected]\node_modules\shiki' -> 'D:\Solutions\my-repo\dist\shiki'

Any help would be appreciated!

Compatibility with vite 4

Probably move peer dep to:

"peerDependencies": {
    "vite": "^3.0.0 || ^4.0.0"
  },

and dev dep to:

"vite": "^4.0.0",

Support preserving timestamps on files

When copying files with this plugin, the copied files with have a fresh timestamp. When publishing the output folder, all files created by this plugin are treated as "new" files and will be redeployed to the destination to replace identical files.

In my scenario, I'm copying ~1500 asset files to an output directory. Then these 1500 files are uploaded on every single deployment.

If I wanted to work around that without modifying this plugin, I would have to only publish files where the contents have not changed (as file size is not a usable indicator in my case). To enable that, all 1500 files need to be downloaded to hash their contents.

Building .ts to .js

is there any feature that allows the building of files like building ts file before copying it

feature request: support URL objects

Modern Node.js APIs have first support for Web Standard URL objects, so it would be useful to have this interface in this plugin as well.

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { viteStaticCopy } from "vite-plugin-static-copy";

// https://vitejs.dev/config/
export default defineConfig({
  base: "/fml-web/",
  plugins: [
    viteStaticCopy({
      targets: [
        {
          src: new URL("lib/foo.wasm", import.meta.url),
          dest: new URL(".", import.meta.url),
        },
      ],
    }),
    react(),
  ],
});

Using structured:true generates wrong path

Hi. Consider we have the following code

// vite.config.mts
export default mergeConfig(baseConfig, {
  ...,
  plugins: [
    viteStaticCopy({
      targets: [
        {
          src: normalizePath(path.resolve(process.cwd(), 'polymer-bundles/calendar/es6-bundled/**')),
          dest: 'polymer-bundles/calendar',
        }
      ],
      structured: true,
    })
  ],
});

I have to make the following changes to copy my files correctly

// node_modules/vite-plugin-static-copy/dist/index.js
// const dirClean = dir.replace(/^(?:\.\.\/)+/, "");
const dirClean = dir.replace(/^(?:\.\.\/)+/, "").replace("/home/admin/Desktop/projects/mln/polymer-bundles/calendar/es6-bundled", "");
const destClean = `${dest}/${dirClean}`.replace(/^\/+|\/+$/g, "");
destDir = destClean;

By default I get wrong path in destClean variable: /home/admin/Desktop/projects/mln/dist/apps/web/app/shell/polymer-bundles/calendar/home/admin/Desktop/projects/mln/polymer-bundles/calendar/es6-bundled
Could you fix this please?
P.S. I use vite with nx. OS ubuntu.

The entire module stopped working

hi~
I made this update progress:
Bump vite-plugin-static-copy from 0.17.0 to 1.0.0 and vite from 4.3.9 to 5.0.10.

Now the module no longer loads on Vite in any way:

✘ [ERROR] "vite-plugin-static-copy" resolved to an ESM file. ESM file cannot be loaded by `require`. See https://vitejs.dev/guide/troubleshooting.html#this-package-is-esm-only for more details. [plugin externalize-deps]
image

When I downgraded, everything went back to normal. So the problem is in the version 1.0.0
Or I renamed the file vite.config.js to vite.config.mjs and this is working now.

Your module was using the file name as a reference to know if it was an ESM or not. pls check and good luck.

feature request: .vue file MIME Type support

I need to use copied .vue files in dev, but .vue MIME type is not in the list of MIME types, so it return a MIME type of "", so i'm unable to import it. I get this error:

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.

it seems like in vite-copy-static-copy/dist/index.js, the var mimes didn't contain the key "vue".
Maybe consider adding it in the list of supported type with a type of application/javascript

`transform` support

Hey, thanks for making this plugin, would it support transform (i.e. modify file contents) like rollup-plugin-copy and CopyWebpackPlugin ?

Copy files to public folder on change when watching

You can now already do

watch: { reloadPageOnChange: true }

But in the system I'm using I refer to the files in the dest folder with a serverpath not a URL.
So it would be nice to have an option to also copy the file on change and then reload the page.

Something like:

watch: {
  reloadPageOnChange: true,
  copyToDest: true,
}

Plugin not work when using with development server

Version: 0.4.2

My config:

// vite.config.ts
export default defineConfig({
  plugins: [
    vue(),
    copy({
      targets: [
        {
          src: [
            'node_modules/cesium/Build/Cesium/Assets',
            'node_modules/cesium/Build/Cesium/ThirdParty',
            'node_modules/cesium/Build/Cesium/Widgets',
            'node_modules/cesium/Build/Cesium/Workers'
          ],
          dest: '/'
        }
      ]
    })
  ],
  // Some more...
})

Assets, ThirdParty, Widgets and Workers are all directories. It worked fun when runing build script. But when I use with npm run dev, I got a lot of 404.

I find that I can let it work if I fallback to version 0.2.

Could you make this package support Node.js v12?

The below error is output in Node.js 12.

failed to load config from C:\Users\cjc\some-project\vite.config.js
error during build:
C:\Users\cjc\some-project\node_modules\vite-plugin-static-copy\dist\index.js:118
    flatten: options.flatten ?? true,
                              ^

SyntaxError: Unexpected token '?'

This is because the ??(Nullish coalescing operator) is not transformed.

Besides, vite supports Node.js >= 12.2.0.

CORS error

Hi,
I am having CORS errors because I am running Vite on a separate domain and this plugin does not send the same CORS headers as Vite itself. Access-Control-Allow-Origin: * should be sent for all assets copied with this plugin.

Compatibility with Nuxt 3?

Great plugin! We've been using it with Nuxt 3, and [email protected] worked great with [email protected]. However, now that Nuxt 3 stable has been released, we're having trouble getting it to work.

Configuration

On a mac using node v18.12.1:

"nuxt": "3.0.0",
"vite-plugin-static-copy": "^0.12.0"
// nuxt.config.ts
import { viteStaticCopy } from "vite-plugin-static-copy";
import path from "node:path";

export default defineNuxtConfig({
  vite: {
    plugins: [
      viteStaticCopy({
        targets: [
          {
            src: path.resolve(__dirname, "./path/to/colors.svg"),
            dest: "copied-files/",
          },
        ],
      }),
    ],
  },
});

Results

On npm run dev, the files aren't copied, and no error is shown.

On npm run build, the following error occurs, and the app fails to build due to missing asset colors.svg:

 ERROR  [vite-plugin-static-copy] Copy count was not set.  

 ERROR  [vite]: Rollup failed to resolve import "/copied-files/colors.svg" from "app.vue".                                                                          09:37:10
This is most likely unintended because it can break your application at runtime.
If you do want to externalize this module explicitly add it to
`build.rollupOptions.external`


 ERROR  [vite]: Rollup failed to resolve import "/copied-files/colors.svg" from "app.vue".                                                                          09:37:10
This is most likely unintended because it can break your application at runtime.
If you do want to externalize this module explicitly add it to
`build.rollupOptions.external`

  This is most likely unintended because it can break your application at runtime.
  If you do want to externalize this module explicitly add it to
  `build.rollupOptions.external`
  at onRollupWarning (node_modules/vite/dist/node/chunks/dep-67e7f8ab.js:45526:19)
  at onwarn (node_modules/vite/dist/node/chunks/dep-67e7f8ab.js:45297:13)
  at Object.onwarn (node_modules/rollup/dist/es/shared/rollup.js:23263:13)
  at ModuleLoader.handleResolveId (node_modules/rollup/dist/es/shared/rollup.js:22158:26)
  at node_modules/rollup/dist/es/shared/rollup.js:22119:26

ERROR: The symbol "X" has already been declared

Problem here during the build:

[vite-plugin-static-copy] Copy count was not set.
error during build:
Error: Transform failed with 4 errors:
<stdin>:1:118: ERROR: The symbol "bc" has already been declared
<stdin>:1:121: ERROR: The symbol "Ui" has already been declared
<stdin>:1:148: ERROR: The symbol "wc" has already been declared
<stdin>:1:160: ERROR: The symbol "ji" has already been declared
    at failureErrorWithLog (/Users/cactus/Documents/Repositories/ui/node_modules/esbuild/lib/main.js:1575:15)
    at /Users/cactus/Documents/Repositories/ui/node_modules/esbuild/lib/main.js:814:29
    at responseCallbacks.<computed> (/Users/cactus/Documents/Repositories/ui/node_modules/esbuild/lib/main.js:680:9)
    at handleIncomingPacket (/Users/cactus/Documents/Repositories/ui/node_modules/esbuild/lib/main.js:735:9)
    at Socket.readFromStdout (/Users/cactus/Documents/Repositories/ui/node_modules/esbuild/lib/main.js:656:7)
    at Socket.emit (node:events:513:28)
    at addChunk (node:internal/streams/readable:324:12)
    at readableAddChunk (node:internal/streams/readable:297:9)
    at Readable.push (node:internal/streams/readable:234:10)
    at Pipe.onStreamRead (node:internal/stream_base_commons:190:23)

In vite.config.ts :

viteStaticCopy({
      targets: [
        { src: resolve('node_modules/@gladiaio/design-system-react/lib/') + '/*', dest: '' },
        { src: resolve('node_modules/web-tree-sitter/tree-sitter.wasm'), dest: '' },
        { src: resolve('node_modules/web-tree-sitter/tree-sitter.wasm'), dest: 'tasks/' },
        { src: resolve('node_modules/curlconverter/dist/tree-sitter-bash.wasm'), dest: '' },
        { src: resolve('node_modules/curlconverter/dist/tree-sitter-bash.wasm'), dest: 'tasks/' },
      ],
    }),

Any idea of what is happening ?

Files are found, but not copied

I can see in the console output that files are found, but I cannot see them being copied anywhere.

Project tree:

  • assets/images/
  • assets/images/folder1/image.jpg
  • assets/images/folder2/file.pdf
  • public/build/manifest.json (generated by Vite)

I am trying to copy everything including the folder structure from assets/images to public/build/images, so for example the assets/images/folder1/image.jpg would end up at public/build/images/folder1/image.jpg

vite.config.js

export default defineConfig({
    plugins: [
        viteStaticCopy({
            targets: [
                {
                    src: path.resolve(__dirname, "assets/images/**/*"),
                    dest: "images",
                },
            ],
            watch: {
                reloadPageOnChange: true,
            },
            flatten: false,
        }),
    ],
})

The console shows that it found bunch of files, but nothing is being copied anywhere, or at least not inside the project folder.
image

Incorrect dest folder

I have used this config in vite,

    viteStaticCopy({
      targets: [
        {
          src: "./src/test.json",
          dest: 'dist',
        },
      ],
      flatten: true,
    }),

but it's being copied on project root nested in full directly tree.
Screenshot 2022-03-28 at 03 32 21

Async transform

Could the transform functions be async? I'd like to run prettier during transform and thats an async process.

Watcher is undefined

I've found that configureServer is not been called probably because i'm not running a server , - just a vite build

 ERROR  error during build:                                                                                                                           10:32:32
TypeError: Cannot read properties of undefined (reading 'close')
    at Object.closeBundle (/Users/ilya/logzio/gaia-hermes-ws/node_modules/vite-plugin-static-copy/dist/index.cjs:949:21)
    at file:///Users/ilya/logzio/gaia-hermes-ws/node_modules/vite/node_modules/rollup/dist/es/shared/rollup.js:23660:40

and this is how plugin is fconfigured:

      plugins: [
        viteStaticCopy({
          targets: [
            { src: 'static', dest: '' },
            { src: 'external-registration', dest: 'static' },
            { src: 'assets/old-webpack-assets/**', dest: 'static/assets' },
          ],
        }),
      ],

am I doing smthng wrong

Add support for Vite 5

Currently, instaling vite-plugin-static-copy along with Vite 5 results in:

➤ YN0060: │ vite is listed by your project with version 5.0.0, which doesn't satisfy what vite-plugin-static-copy requests (^3.0.0 || ^4.0.0).

According to my tests, it looks like updating it is gonna be as easy as updating the list of peerDependencies.

Documentation: Some words on what "good uses" for this package are would be welcome

The readme currently notes:

Before you use this plugin, consider using public directory or import in JavaScript. In most cases, these will work.

However, I keep coming back to this plugin because of the glob and dynamic import limitations in vite, so I thought I'd ask here if that is actually an expected usecase, and potentially some notes on that can go into the readme.

Consider an example structure for a photo albums project, and some photos have a story markdown file.
The photo album is on a specific location on disk, unrelated to the vite project (using sveltekit here, but shouldn't matter for the question). There are some topics and subtopics where photos are categorized in.
It is not viable nor desired to just copy the entire set of photo albums into the public directory.

- someDirectoryOnDisk
  - topic1
    - photo1.png
    - story1.md
    - photo2.png
    - subtopic
      - photo3.png
      - story3.md
  - topic2
    - photo3.png
    - story4.md

Somewhere else on disk, we have a svelte project:

- someDevDirectory
  - package.json
  - vite.config.ts
  - src/routes
    - +page.server.ts
    - +page.svelte

Would you say that is a typical usecase for vite-plugin-static-copy?

The flow would be:

  • make a utility method that collects absolute paths and desired relative paths for all items
  • invoke that from vite.config.ts and use vite-plugin-static-copy to ensure the files end up in the build
  • invoke it also from +page.server.ts to pass all the relative paths to +page.svelte

It feels "glued together" compared to letting vite handle all imports and file copying, but I can't figure out if/how that would work given the limitations of import.meta.glob and dynamic import with a single variable. Letting vite handle it would also allow using image optimizations etc., that seem harder to add this way.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.