fer*_*mmm 6 webpack webpack-style-loader webpack-2 webpack-4
我正在使用一个节点库,其中包含一个css文件,该css文件加载这样的图像
background-image: url("image.png");
Run Code Online (Sandbox Code Playgroud)
在http:// localhost:9000 /处请求文件“ image.png” (根目录)很脏,无法在项目的整个根目录中包含图像。
另外我还有另一个问题,我不知道为什么模块的图像文件没有自动复制到构建文件夹,仅当我手动将图像文件复制到构建文件夹时才起作用。使用Webpack配置参数时,我正在使用该功能将映像复制到根目录,但是它为它们添加了随机名称,因此我不想在根目录中使用它们。
我希望将所有加载的图像复制到带有原始文件名的build文件夹内的“ img”子文件夹中,并在此处进行请求,因此根目录不会弄脏那里的所有文件。
这是我的webpack配置文件:
var webpack = require('webpack');
var WebpackNotifierPlugin = require('webpack-notifier');
"use strict";
module.exports = {
entry: "./source/typescript/Main.ts",
output: {
filename: "./js/bundle.js"
},
devtool: "inline-source-map",
devServer: {
contentBase: ".",
host: "localhost",
port: 9000,
open: true
},
module: {
rules: [
{
test:/\.(s*)css$/,
use: [
{
loader: "style-loader"
},
{
loader: "css-loader",
options: {
url: false
}
},
{
loader: "sass-loader"
}
]
},
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
},
{
enforce: 'pre',
test: /\.js$/,
loader: "source-map-loader"
},
{
test: /\.(png|jpg|gif|svg|eot|ttf|otf|woff|woff2|json|xml|ico)$/,
use: [{loader: 'file-loader'}]
},
{
test: /\.(csv|tsv)$/,
use: [{ loader: 'csv-loader' }]
},
{
test: /\.exec\.js$/,
use: [{ loader: 'script-loader' }]
},
{
test: require.resolve('jquery'),
use:
[
{
loader: 'expose-loader',
options: 'jQuery'
},
{
loader: 'expose-loader',
options: '$'
}
]
}
]
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ]
},
plugins: [
new WebpackNotifierPlugin({excludeWarnings: true}),
//new webpack.optimize.UglifyJsPlugin({compress: {warnings: false}}) // Uncoment to minify bundle
]
};
Run Code Online (Sandbox Code Playgroud)
我解决了这些问题:
"outputPath" 和 "name" 参数可用于告诉 webpack 将所有图像文件复制到构建文件夹中的特定文件夹中,并使用特定的命名规则。所以我解决了这样的问题:
1)随机文件名复制到根目录的解决方案:我更改了webpack配置文件,告诉webpack加载的任何图像都应该以其原始名称复制到img子文件夹内的build文件夹中。这是在文件加载器选项中使用“outputPath”和“name”参数完成的。
2)图片文件没有被复制到build文件夹的解决方法:去掉css-loader中的"url:false",现在路径由css-loader管理。(默认行为)。我最初设置该选项是因为我不明白 css-loader 如何解析 url,所以我禁用了该功能,因为它抛出了一些错误。现在我意识到 css url() 路径是相对于以 / 开头的项目的根目录,例如: url("/img/my-image.png"); 这阻止了 webpack 将图像文件复制到构建文件夹。
现在一切正常,我对 loader 的最终 webpack 配置是这样的:
module: {
rules: [
{
test: /\.(png|jpg|gif|svg|ico)$/,
loader: 'file-loader',
query:{
outputPath: './img/',
name: '[name].[ext]?[hash]'
}
},
{
test: /\.(eot|ttf|otf|woff|woff2|json|xml)$/,
loader: 'file-loader',
query:{
outputPath: './fonts/',
name: '[name].[ext]?[hash]'
}
},
{
test: /\.(json|xml)$/,
loader: 'file-loader',
query:{
outputPath: './data/',
name: '[name].[ext]?[hash]'
}
},
{
test: /\.(s*)css$/,
use: [{ loader: "style-loader" }, { loader: "css-loader" }, { loader: "sass-loader" }]
},
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
},
{
enforce: 'pre',
test: /\.js$/,
loader: "source-map-loader"
},
{
test: /\.(csv|tsv)$/,
use: [{ loader: 'csv-loader' }]
},
{
test: /\.exec\.js$/,
use: [{ loader: 'script-loader' }]
}
]
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5003 次 |
| 最近记录: |