demo目录:
1.将css打包到js内部
配置文件./conf/webpack.dev.js:
const path = require("path"); module.exports = { mode: "development", //打包为开发模式 entry: "./src/main", //入口文件,从项目根目录指定 output: { //输出路径和文件名,使用path模块resolve方法将输出路径解析为绝对路径 path: path.resolve(__dirname, "../dist/js"), //将js文件打包到dist/js的目录 filename: "main.js" }, module: { rules: [ { test: /.css$/, use: [ { loader:"style-loader" }, { loader:"css-loader" } ] } ] } }
安装style-loader和css-loader,css-loader用于解析css,style-loader用于将css插入html文档中
npm install style-loader css-loader --save-dev
打包:
webpack --config=conf/webpack.dev.js
2.将css打包成单独的css文件
2.1.使用extract-text-webpack-plugin插件
安装extract-text-webpack-plugin,加上@next安装该插件的最新版,现版本不适用
npm install --save-dev extract-text-webpack-plugin@next
在项目目录下安装webpack-cli和webpack
npm install webpack webpack-cli
如果打包的时候以下错误,说明漏掉这一步:
ming@ming-TM1604:/home/wwwroot/ming/wb2$ webpack --config=conf/webpack.dev.js
/usr/local/lib/node_modules/webpack-cli/bin/cli.js:244
throw err;
^
Error: Cannot find module 'webpack/lib/Chunk'
at Function.Module._resolveFilename (module.js:543:15)
at Function.Module._load (module.js:470:25)
at Module.require (module.js:593:17)
配置文件./conf/webpack.dev.js:
const ExtractTextPlugin = require("extract-text-webpack-plugin"); const path = require("path"); module.exports = { mode: "development", //打包为开发模式 entry: "./src/main", //入口文件,从项目根目录指定 output: { //输出路径和文件名,使用path模块resolve方法将输出路径解析为绝对路径 path: path.resolve(__dirname, "../dist/js"), //将js文件打包到dist/js的目录 filename: "main.js" }, module: { rules: [ { test: /.css$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: "css-loader" }) } ] }, plugins: [ new ExtractTextPlugin("../css/styles.css") //默认其实目录问打包后的入口文件路径,所以需要../ ] }
打包完成后会在dist目录下生成css/styles.css文件
注:由于与webpack4兼容性问题,打包会提示Entrypoint undefined = extract-text-webpack-plugin-output-filename
2.2.使用mini-css-extract-plugin插件
配置文件./conf/webpack.dev.js:
const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const path = require("path"); module.exports = { mode: "development", //打包为开发模式 entry: "./src/main", //入口文件,从项目根目录指定 output: { //输出路径和文件名,使用path模块resolve方法将输出路径解析为绝对路径 path: path.resolve(__dirname, "../dist/js"), //将js文件打包到dist/js的目录 filename: "main.js" }, module: { rules: [ { test: /.css$/, use: [ MiniCssExtractPlugin.loader, { loader: "css-loader", options: { minimize: true } }, ] } ] }, plugins: [ new MiniCssExtractPlugin({ filename: "../css/styles.css" //如果需要将css文件单独放入css文件夹中需要../ }) ] }
打包完成后也会在dist目录下生成css/styles.css文件
————————————————
版权声明:本文为CSDN博主「骑着代码去流浪」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_36185028/article/details/81120276