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

查看:162
本文介绍了如何使用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 )并返回该文件的散列网址。

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天全站免登陆