网上有很多关于如何分开打包js和css文件,发现存在有很多问题(比如:webpack3配置和webpack4配置有些不同、文章内容不全面等),采坑过程中走了很多歪路
以下直接贴出代码
1、package.json配置
采坑点:webpack4需要mini-css-extract-plugin来分开打包css文件,不能用extract-text-webpack-plugin 不支持了webpack4
{
"name": "webpack_test",
"version": "1.0.0",
"main": "a.js",
"scripts": {
"build": "webpack --progress --watch",
"server": "webpack-dev-server --content-base ./"
},
"author": "",
"license": "ISC",
"keywords": [],
"description": "",
"dependencies": {
"lodash": "^4.17.11",
"moment": "^2.22.2"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-env": "^1.7.0",
"babel-preset-es2015": "^6.24.1",
"css-loader": "^2.0.1",
"mini-css-extract-plugin": "^0.5.0", //支持webpack4
"style-loader": "^0.23.1",
"webpack": "^4.27.1",
"webpack-cli": "^3.1.2",
"webpack-dev-server": "^3.1.10"
}
}
3、webpack.config.js配置
采坑点:“style-loader”“css-loader”“MiniCssExtractPlugin.loader”顺序问题,先css-loader编译css文件,再用MiniCssExtractPlugin分开打包css文件,最后用style-loader将css加载到页面上。
const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
devtool: 'source-map',
entry: {
'a': [path.resolve(__dirname, 'assets/source/js/a.js')]
},
output: {
path: path.resolve(__dirname, 'assets/dist/js'),
filename: '[name]-buddle.js'
},
module: {
rules: [
{
test: /\.css$/,
use: [
"style-loader",
MiniCssExtractPlugin.loader,
"css-loader"
]
},
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: [
{
loader: 'babel-loader',
options: { presets: ['es2015'] }
}
]
}
]
},
plugins:[
new MiniCssExtractPlugin({
filename: "../css/[name]-buddle.css"
})
]
}
3、cnpm run build -----执行webpack打包
4、cnpm run server -----启动服务