I’m trying to pack web resources into my Rust binary. My plan is to use npm install
to get the stuff I need, then bundle the JavaScript into one file. After that, I want to turn it into a Rust file.
I’m using the static-files
crate in my build.rs
to handle all this. It works fine, but I hit a snag when I try to publish my crate to crates.io
. The problem is that npm install
puts files outside the OUT_DIR
, which causes an error.
The error message says the source directory was changed by build.rs
during publishing. It tells me build scripts shouldn’t change anything outside OUT_DIR
.
I thought about using .target(env::var("OUT_DIR").unwrap())
to put the generated files in OUT_DIR
, but that doesn’t fix where node_modules
ends up.
Any ideas on how to make this work within the OUT_DIR
limits? I really want to be able to publish my crate without these issues.
I’ve dealt with similar issues in my projects. One approach that worked for me was using a custom npm cache directory within OUT_DIR. You can set this up by adding npm config set cache $OUT_DIR/npm-cache
before your npm install command in build.rs. This keeps all npm-related files within OUT_DIR.
Another trick I found useful was to use a package bundler like webpack or rollup directly in your build script. This way, you can avoid npm install altogether and just bundle your dependencies from a package.json file. It’s a bit more work to set up, but it gives you more control over the process and keeps everything in OUT_DIR.
If you’re open to changing your approach, you might consider using a tool like wasm-pack. It’s designed for Rust/WebAssembly projects and handles a lot of these integration issues out of the box. It might save you some headaches in the long run.
Consider using a temporary directory for the npm install process. You could create a subfolder within OUT_DIR, run npm install there, bundle your JavaScript, and then clean up unnecessary files. This approach keeps everything contained within OUT_DIR.
Another option is to pre-build your npm dependencies and include only the bundled JavaScript file in your crate. This way, you avoid the npm install step during the build process altogether.
If these solutions aren’t feasible, you might need to rethink your build strategy. Perhaps separating the web resource bundling into a separate step before cargo build could be a workaround. This would allow you to have more control over the file locations without conflicting with cargo’s publishing restrictions.
Hey Stella_Dreamer, that’s a tricky one! Have u tried running npm install with a custom prefix? Like npm install --prefix $OUT_DIR
. That might force node_modules into OUT_DIR. If that doesnt work, maybe copy just the files u need from node_modules to OUT_DIR b4 bundling? Just brainstorming here, hope it helps!