我正试着从Gulp转到Webpack。在Gulp中,我有一个任务,它将所有文件和文件夹从/static/文件夹复制到/build/文件夹。如何用Webpack做同样的事情?我需要一些插件吗?
当前回答
如果你想复制静态文件,你可以这样使用文件加载器:
对于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文件的位置。
你可以对图像或其他东西做同样的事情。 语境是一种强大的探索方法!!
其他回答
在我的例子中,我使用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都会产生问题。
希望它能帮助到一些人。
你可以在package.json中编写bash:
# package.json
{
"name": ...,
"version": ...,
"scripts": {
"build": "NODE_ENV=production npm run webpack && cp -v <this> <that> && echo ok",
...
}
}
你不需要到处复制东西,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" }
]
}
};
当然,您需要首先安装文件加载器才能使其工作。
最有可能的是,你应该使用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')
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)
推荐文章
- AngularJS:工厂和服务?
- js:将一个组件包装成另一个组件
- 父ng-repeat从子ng-repeat的访问索引
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;
- JS字符串“+”vs concat方法
- AngularJS使用ng-class切换类
- 访问Handlebars.js每次循环范围之外的变量
- 如何用JavaScript截屏一个div ?
- 如何为其他域设置cookie