背景描述:webpack插件功能强大且可以定制,可以使用extract-text-webpack-plugin的插件来把散落在各地的css提取出来,并生成一个main.css的文件,最终在index.html通过<link>的形式加载它。
配置文件webpack.config.js
var path=require('path');
//导入插件
var ExtractTextPlugin=require('extract-text-webpack-plugin');
var config={
entry:{
main:'./main'
},
output:{
path:path.join(__dirname,'./dist'),
publicPath:'/dist',
filename:'main.js'
},
module:{
rules:[
{
test:/\.css$/,
use:ExtractTextPlugin.extract({
use:'css-loader',
fallback:'style-loader'
})
}
]
},
plugins:[
//重命名提取后的css文件
new ExtractTextPlugin("main.css")
]
};
module.exports=config;
index.html加载css文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>webpack App</title>
<link rel="stylesheet" type="text/css" href="/dist/main.css">
</head>
<body>
<div id="app">
Hello Webpack.
</div>
<script type="text/javascript" src="/dist/main.js"></script>
</body>
</html>
执行command:
cnpm run dev
执行后报错:
Object.defineProperty(Chunk.prototype, "entrypoints", {
configurable: false,
get() {
throw new Error(
"Chunk.entrypoints: Use Chunks.groupsIterable and filter by instanceof Entrypoint instead"
);
},
set() {
throw new Error("Chunk.entrypoints: Use Chunks.addGroup instead");
}
});
分析原因:extract-text-webpack-plugin还不能支持webpack4.0.0以上的版本。查看package.json中的版本信息:
"style-loader": "^0.23.1",
"webpack": "^4.30.0",
"webpack-cli": "^3.3.1",
"webpack-dev-server": "^3.3.1"
解决方法:
cnpm install --save-dev extract-text-webpack-plugin@next
会下载到 "extract-text-webpack-plugin": "^4.0.0-beta.0",之后再打包就正常了