我正试着从Gulp转到Webpack。在Gulp中,我有一个任务,它将所有文件和文件夹从/static/文件夹复制到/build/文件夹。如何用Webpack做同样的事情?我需要一些插件吗?
当前回答
我加载静态图像和字体的方式:
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/'
},
}
]
}
不要忘记安装文件加载器来让它工作。
其他回答
如果你想复制静态文件,你可以这样使用文件加载器:
对于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文件的位置。
你可以对图像或其他东西做同样的事情。 语境是一种强大的探索方法!!
我加载静态图像和字体的方式:
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/'
},
}
]
}
不要忘记安装文件加载器来让它工作。
在我的例子中,我使用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都会产生问题。
希望它能帮助到一些人。
我也被困在这里了。Copy-webpack-plugin对我有用。
然而,'copy-webpack-plugin'在我的情况下是不必要的(我后来才知道)。
Webpack忽略根路径 例子
<img src="/images/logo.png'>
因此,在不使用copy-webpack-plugin的情况下实现此功能 在路径中使用“~”
<img src="~images/logo.png'>
'~'告诉webpack将'images'视为一个模块
注意: 您可能必须在中添加images目录的父目录
resolve: {
modules: [
'parent-directory of images',
'node_modules'
]
}
访问https://vuejs-templates.github.io/webpack/static.html
最有可能的是,你应该使用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')