webpack中加载CSS

webpack强大之处在于可以将CSS当做一个资源模块进行管理和加载

基本使用:

安装webpack的加载插件style-loader和css-loader:

npm install style-loader css-loader --save-dev

修改配置文件webpack.config.js:

var webpack = require('webpack');

module.exports = {
	//context: __dirname + "/src", //指定了工作的目录,相当如base路径
	entry: "./src/app.js",
	output: {
		path: __dirname + "/dist",
		filename: "bundle.js"
	},
	devtool: "#source-map",
	module: {
		loaders: [
			// Transpile any JavaScript file:
			{
				test: /\.js$/,
				exclude: /node_modules/,
				loader: 'babel-loader'
			}, {
				test: /\.css$/,
				loader: 'style-loader!css-loader'
			},
		]
	},
	resolve: {
		alias: { //将常用的lib在这里设置别名
			//"bootstrap.css": "bootstrap/dist/css/bootstrap.css"
		}
	}

test: /\.css$/这里设置了加载器

app.js中

require("./test.css");

最后执行webpack命令,test.css会被打包到bundle.js中。。。。NB

上面的方式会将CSS打包到JS文件中,虽然很NB但总归是怪怪的

没关系,还是有方案将css单独拿出来的,这里用到另一个插件extract-text-webpack-plugin
还是先安装

npm install extract-text-webpack-plugin --save

修改配置文件如下:

var webpack = require('webpack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
	//context: __dirname + "/src", //指定了工作的目录,相当如base路径
	entry: "./src/app.js",
	output: {
		path: __dirname + "/dist",
		filename: "bundle.js"
	},
	devtool: "#source-map",
	module: {
		loaders: [
			// Transpile any JavaScript file:
			{
				test: /\.js$/,
				exclude: /node_modules/,
				loader: 'babel-loader'
			}, {
				test: /\.css$/,
				loader: ExtractTextPlugin.extract("style-loader", "css-loader")
			},
		]
	},
	resolve: {
		alias: { //将常用的lib在这里设置别名
			//"bootstrap.css": "bootstrap/dist/css/bootstrap.css"
		}
	},
	// Use the plugin to specify the resulting filename (and add needed behavior to the compiler)
    plugins: [
        new ExtractTextPlugin("[name].css")
    ]
}

执行命令,这时候dist里面会有多出来的.css文件了

将多个CSS文件打包到一个CSS文件

还是上面的配置文件,修改下面的地方:

plugins: [
    new ExtractTextPlugin("style.css", {
        allChunks: true
    })
]

将公共部分隔离出去

new webpack.optimize.CommonsChunkPlugin("commons", "commons.js"),
new ExtractTextPlugin("[name].css")

参考:
https://webpack.github.io/docs/stylesheets.html

posted @ 2015-11-27 10:37  le0zh  阅读(3103)  评论(0编辑  收藏  举报