如何使用 Webpack 将静态文件复制到构建目录? [英] How to copy static files to build directory with Webpack?

查看:46
本文介绍了如何使用 Webpack 将静态文件复制到构建目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 Gulp 迁移到 Webpack.在 Gulp 中,我有将所有文件和文件夹从 /static/ 文件夹复制到 /build/ 文件夹的任务.如何使用 Webpack 做同样的事情?我需要一些插件吗?

I'm trying to move from Gulp to Webpack. In Gulp I have task which copies all files and folders from /static/ folder to /build/ folder. How to do the same with Webpack? Do I need some plugin?

推荐答案

你不需要到处复制东西,webpack 的工作方式与 gulp 不同.Webpack 是一个模块捆绑器,您在文件中引用的所有内容都将包含在内.你只需要为此指定一个加载器.

You don't need to copy things around, webpack works different than gulp. Webpack is a module bundler and everything you reference in your files will be included. You just need to specify a loader for that.

所以如果你写:

var myImage = require("./static/myImage.jpg");

Webpack 将首先尝试将引用的文件解析为 JavaScript(因为这是默认设置).当然,那会失败.这就是您需要为该文件类型指定加载器的原因.文件- 或 url-loader 例如获取引用的文件,将其放入 webpack 的输出文件夹(在您的情况下应该是 build)并返回散列的 url那个文件.

Webpack will first try to parse the referenced file as JavaScript (because that's the default). Of course, that will fail. That's why you need to specify a loader for that file type. The file- or url-loader for instance take the referenced file, put it into webpack's output folder (which should be build in your case) and return the hashed url for that file.

var myImage = require("./static/myImage.jpg");
console.log(myImage); // '/build/12as7f9asfasgasg.jpg'

通常通过 webpack 配置应用加载器:

Usually loaders are applied via the webpack config:

// webpack.config.js

module.exports = {
    ...
    module: {
        loaders: [
            { test: /.(jpe?g|gif|png|svg|woff|ttf|wav|mp3)$/, loader: "file" }
        ]
    }
};

当然,您需要先安装文件加载器才能完成这项工作.

Of course you need to install the file-loader first to make this work.

这篇关于如何使用 Webpack 将静态文件复制到构建目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆