1.下载依赖
cnpm i css-loader style-loader --save-dev
2.webpack.config.js【css加载】
const path=require('path');
//webpack生成html
const HtmlWebpackPlugin=require('html-webpack-plugin');
const PATHS={
app: path.join(__dirname, 'app'),
build: path.join(__dirname, 'build'),
};
module.exports={
devServer:{
host: process.env.HOST, //Defaults to 'localhost
port: 80, //Defalut to 8080
// overlay: true captures only errors
overlay: {
errors: true,
warnings: true,
},
},
entry:{
app:PATHS.app,
},
output: {
path: PATHS.build,
filename: '[name].js',
},
module:{
rules:[
//eslint检测js
{
test: /\.js$/,
enforce: 'pre',
loader:'eslint-loader',
options:{
emitWarning: true,
},
},
//css加载,执行顺序,先css-loader再style-loader
{
test: /\.css$/,
use: ['style-loader','css-loader'],
}
],
},
plugins:[
//生成html
new HtmlWebpackPlugin({
title: 'Webpack demo',
}),
],
};
3.webpack.config.js【css作用域】
const path=require('path');
const HtmlWebpackPlugin=require('html-webpack-plugin');
const PATHS={
app: path.join(__dirname, 'app'),
build: path.join(__dirname, 'build'),
};
module.exports={
devServer:{
host: process.env.HOST, //Defaults to 'localhost
port: 80, //Defalut to 8080
// overlay: true captures only errors
overlay: {
errors: true,
warnings: true,
},
},
entry:{
app:PATHS.app,
},
output: {
path: PATHS.build,
filename: '[name].js',
},
module:{
rules:[
{
test: /\.js$/,
enforce: 'pre',
loader:'eslint-loader',
options:{
emitWarning: true,
},
},
//不同作用域css
{
test: /\.css$/,
exclude: /node_modules/,
use: [
'style-loader',
{
loader:'css-loader',
options: {
modules: true,
},
}
],
}
],
},
plugins:[
new HtmlWebpackPlugin({
title: 'Webpack demo',
}),
],
};
4.分离css至不同的文件
(1)下载依赖
cnpm i extract-text-webpack-plugin@next --save-dev
(2)webpack.config.js
const path=require('path');
const HtmlWebpackPlugin=require('html-webpack-plugin');
//css打包分离
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const PATHS={
app: path.join(__dirname, 'app'),
build: path.join(__dirname, 'build'),
};
//css打包分离
const plugin = new ExtractTextPlugin({
filename: '[name].css',
ignoreOrder: true,
})
module.exports={
devServer:{
host: process.env.HOST, //Defaults to 'localhost
port: 80, //Defalut to 8080
// overlay: true captures only errors
overlay: {
errors: true,
warnings: true,
},
},
entry:{
app:PATHS.app,
},
output: {
path: PATHS.build,
filename: '[name].js',
},
module:{
rules:[
{
test: /\.js$/,
enforce: 'pre',
loader:'eslint-loader',
options:{
emitWarning: true,
},
},
//css打包分离
{
test: /\.css$/,
exclude: /node_modules/,
use: plugin.extract({
use: {
loader: 'css-loader',
options: {
modules: true,
},
},
fallback : 'style-loader',
}),
}
],
},
plugins:[
new HtmlWebpackPlugin({
title: 'Webpack demo',
}),
//css打包分离
plugin,
],
};
3.运行
npm run start
npm run build