index.js
写的代码了。
path.resolve([...paths]) 方法会把一个路径或路径片段的序列解析为一个绝对路径。
使用 html-webpack-plugin 创建 html 文件
更多情况下我们不希望打包一次,就新建一次 html 文件来引用打包后的文件,这样显得不智能或者说当你打包的文件名修改后,引用路径就会出错。
这个时候我们就可以使用html-webpack-plugin 插件来将 HTML 引用路径和我们的构建结果关联起来。
npm install html-webpack-plugin -D
创建文件 public/index.html
修改 webpack.config.js
文件
const HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { //... plugins: [ new HtmlWebpackPlugin({ filename: 'index.html', // 配置输出文件名和路径 template: './public/index.html' // 配置要被编译的html文件 }) ] }
重新执行 npm run build
, dist 目录就会多个 index.html
并引入了 bundle.js
.
压缩 html 文件
修改 webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { //... plugins: [ new HtmlWebpackPlugin({ filename: 'index.html', // 配置输出文件名和路径 template: './public/index.html', // 配置要被编译的html文件 hash: true, // 压缩 => production 模式使用 minify: { removeAttributeQuotes: true, //删除双引号 collapseWhitespace: true //折叠 html 为一行 } }) ] }
打包 css 文件
我们希望使用 webpack 来进行构建 css 文件,,为此,需要在配置中引入 loader 来解析和处理 CSS 文件:
npm install style-loader css-loader -D
新建 src/assets/style/color.css
, 修改 webpack.config.js
文件:
module.exports = { //... module: { /** * test: 匹配特定条件。一般是提供一个正则表达式或正则表达式的数组 * include: 匹配特定条件。一般是提供一个字符串或者字符串数组 * exclude: 排除特定条件 * and: 必须匹配数组中的所有条件 * or: 匹配数组中任何一个条件, * nor: 必须排除这个条件 */ rules: [ { test: /\.css$/, include: [path.resolve(__dirname, 'src')], use: ['style-loader', 'css-loader'] } ] } //... }
经由上述两个 loader 的处理后,CSS 代码会转变为 JS, 如果需要单独把 CSS 文件分离出来,我们需要使用 mini-css-extract-plugin 插件
抽取 css 到独立文件, 自动添加前缀
npm i mini-css-extract-plugin postcss-loader autoprefixer -D
内容版权声明:除非注明,否则皆为本站原创文章。