我正试着从Gulp转到Webpack。在Gulp中,我有一个任务,它将所有文件和文件夹从/static/文件夹复制到/build/文件夹。如何用Webpack做同样的事情?我需要一些插件吗?
当前回答
One advantage that the aforementioned copy-webpack-plugin brings that hasn't been explained before is that all the other methods mentioned here still bundle the resources into your bundle files (and require you to "require" or "import" them somewhere). If I just want to move some images around or some template partials, I don't want to clutter up my javascript bundle file with useless references to them, I just want the files emitted in the right place. I haven't found any other way to do this in webpack. Admittedly it's not what webpack originally was designed for, but it's definitely a current use case. (@BreakDS I hope this answers your question - it's only a benefit if you want it)
其他回答
最有可能的是,你应该使用CopyWebpackPlugin,这是在kevlened回答中提到的。另外,对于某些类型的文件,如.html或.json,你也可以使用raw-loader或json-loader。通过npm Install -D raw-loader安装它,然后你只需要在webpack.config.js文件中添加另一个加载器。
如:
{
test: /\.html/,
loader: 'raw'
}
注意:重启webpack-dev-server以使任何配置更改生效。
现在你可以要求html文件使用相对路径,这使得它更容易移动文件夹。
template: require('./nav.html')
你不需要到处复制东西,webpack的工作方式与gulp不同。Webpack是一个模块捆绑器,你在文件中引用的所有内容都将被包括在内。你只需要为此指定一个加载器。
所以如果你写:
var myImage = require("./static/myImage.jpg");
Webpack将首先尝试将引用的文件解析为JavaScript(因为这是默认的)。当然,这将会失败。这就是为什么您需要为该文件类型指定一个加载器。例如,文件或url加载器获取引用的文件,将其放入webpack的输出文件夹(在您的情况下应该是构建的),并返回该文件的散列url。
var myImage = require("./static/myImage.jpg");
console.log(myImage); // '/build/12as7f9asfasgasg.jpg'
通常加载器是通过webpack配置来应用的:
// webpack.config.js
module.exports = {
...
module: {
loaders: [
{ test: /\.(jpe?g|gif|png|svg|woff|ttf|wav|mp3)$/, loader: "file" }
]
}
};
当然,您需要首先安装文件加载器才能使其工作。
你可以在package.json中编写bash:
# package.json
{
"name": ...,
"version": ...,
"scripts": {
"build": "NODE_ENV=production npm run webpack && cp -v <this> <that> && echo ok",
...
}
}
在我的例子中,我使用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
} )
}
推荐文章
- 反应钩子-正确的方式清除超时和间隔
- TypeScript枚举对象数组
- 在React.js中正确的img路径
- 在React.js中更新组件onScroll的样式
- onClick ReactJS调用多个函数
- 如何在JavaScript中转义单引号(')?
- Ng-repeat结束事件
- 谷歌MAP API未捕获的类型错误:无法读取属性“offsetWidth”为空
- 模糊vs聚焦-有什么真正的区别吗?
- 如何使用JavaScript创建和样式一个div ?
- 清除JavaScript中的缓存
- 如何在使用Javascript替换DOM元素?
- 在Redux应用程序中哪里写localStorage ?
- 如何在ReactJS中从“外部”访问组件方法?
- 为时刻添加持续时间(moment.js)