Next.js+React实现docx文件点击下载编译报错求助
Hey there! Let's get that docx download button working for you. The error you're seeing—Failed to compile Module parse failed: Unexpected character—happens because Next.js's default webpack configuration doesn't know how to handle non-standard static files like docx out of the box. It tries to parse the file as JavaScript, which obviously breaks things.
Here are two solid solutions to fix this:
Solution 1: Use the public Directory (Simplest Approach)
Next.js has a dedicated public folder for static assets that don't need webpack processing. This is the easiest way to make your docx downloadable:
- Move your
Gate-Pass-Moving-in.docxfile intopublic/images/downloads/(create the folders if they don't exist). - Update your link to use the root-relative path of the file:
<a href="/images/downloads/Gate-Pass-Moving-in.docx" className="btn btn-sm btn-secondary" download> Download </a>
Files in the public directory are served directly from the root of your site, so you don't need to import or require them—just reference the path directly. This skips webpack's parsing entirely, so no more errors.
Solution 2: Configure Webpack to Handle Docx Files
If you prefer to keep the docx in your existing images/downloads directory, you can tell webpack how to process it using file-loader:
First, install
file-loaderas a dev dependency:npm install file-loader --save-dev # Or with yarn yarn add file-loader --devCreate or update your
next.config.jsfile in the root of your project with this webpack configuration:/** @type {import('next').NextConfig} */ const nextConfig = { webpack: (config) => { // Add rule to handle docx files config.module.rules.push({ test: /\.docx$/, use: [ { loader: 'file-loader', options: { name: '[path][name].[ext]', publicPath: '/_next', }, }, ], }); return config; }, }; module.exports = nextConfig;Now you can use your original import approach without errors:
import moveIn from "../../images/downloads/Gate-Pass-Moving-in.docx"; <a href={moveIn} className="btn btn-sm btn-secondary" download> Download </a>
This config tells webpack to use file-loader to copy the docx file to your build output and return the correct URL for it.
Recommendation
Stick with Solution 1 if you can—it's simpler and aligns with Next.js's recommended way of handling static assets. No extra dependencies or config changes needed!
内容的提问来源于stack exchange,提问作者Mahendra Pratap

