我正试着从Gulp转到Webpack。在Gulp中,我有一个任务,它将所有文件和文件夹从/static/文件夹复制到/build/文件夹。如何用Webpack做同样的事情?我需要一些插件吗?
当前回答
在我的例子中,我使用webpack作为wordpress插件来压缩js文件,其中插件文件已经被压缩了,需要跳过这个过程。
optimization: {
minimize: false,
},
externals: {
"jquery": "jQuery",
},
entry: glob.sync('./js/plugin/**.js').reduce(function (obj, el) {
obj[path.parse(el).name] = el;
return obj
}, {}),
output: {
path: path.resolve(__dirname, './js/dist/plugin'),
filename: "[name].js",
clean: true,
},
用于将js文件复制到build文件夹。使用任何其他方法,如文件加载器和复制webpack都会产生问题。
希望它能帮助到一些人。
其他回答
webpack配置文件(在webpack 2中)允许你导出承诺链,只要最后一步返回一个webpack配置对象。参见承诺配置文档。从这里开始:
webpack现在支持从配置文件中返回Promise。这允许在配置文件中进行异步处理。
你可以创建一个简单的递归复制函数来复制你的文件,并且只在触发webpack之后。例如:
module.exports = function(){
return copyTheFiles( inpath, outpath).then( result => {
return { entry: "..." } // Etc etc
} )
}
我加载静态图像和字体的方式:
module: {
rules: [
....
{
test: /\.(jpe?g|png|gif|svg)$/i,
/* Exclude fonts while working with images, e.g. .svg can be both image or font. */
exclude: path.resolve(__dirname, '../src/assets/fonts'),
use: [{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'images/'
}
}]
},
{
test: /\.(woff(2)?|ttf|eot|svg|otf)(\?v=\d+\.\d+\.\d+)?$/,
/* Exclude images while working with fonts, e.g. .svg can be both image or font. */
exclude: path.resolve(__dirname, '../src/assets/images'),
use: [{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/'
},
}
]
}
不要忘记安装文件加载器来让它工作。
以上建议都很好。但是为了直接回答你的问题,我建议在package.json中定义的脚本中使用cpy-cli。
本例期望node位于路径上的某个位置。将cpy-cli安装为开发依赖项:
NPM install——save-dev cpy-cli
然后创建两个nodejs文件。一个用于复制,另一个用于显示复选标记和消息。
copy.js
#!/usr/bin/env node
var shelljs = require('shelljs');
var addCheckMark = require('./helpers/checkmark');
var path = require('path');
var cpy = path.join(__dirname, '../node_modules/cpy-cli/cli.js');
shelljs.exec(cpy + ' /static/* /build/', addCheckMark.bind(null, callback));
function callback() {
process.stdout.write(' Copied /static/* to the /build/ directory\n\n');
}
checkmark.js
var chalk = require('chalk');
/**
* Adds mark check symbol
*/
function addCheckMark(callback) {
process.stdout.write(chalk.green(' ✓'));
callback();
}
module.exports = addCheckMark;
将脚本添加到package.json中。假设脚本在<project-root>/scripts/
...
"scripts": {
"copy": "node scripts/copy.js",
...
运行脚本:
NPM运行拷贝
如果你想复制静态文件,你可以这样使用文件加载器:
对于HTML文件:
在webpack.config.js中:
module.exports = {
...
module: {
loaders: [
{ test: /\.(html)$/,
loader: "file?name=[path][name].[ext]&context=./app/static"
}
]
}
};
在js文件中:
require.context("./static/", true, /^\.\/.*\.html/);
./static/相对于js文件的位置。
你可以对图像或其他东西做同样的事情。 语境是一种强大的探索方法!!
你可以在package.json中编写bash:
# package.json
{
"name": ...,
"version": ...,
"scripts": {
"build": "NODE_ENV=production npm run webpack && cp -v <this> <that> && echo ok",
...
}
}