處理項目中的模版文件

安裝 html-loader

cnpm i html-loader -D

配置

{
  test:/\.html$/,
  loader: ['html-loader']
}

下面模擬一個完整的vue打包

項目目錄:

 

layer.html:

<div class="wrapper">
  <div>layer is test</div>
</div>

layer.less

.wrapper {
  color: red;
  width: 30px;
  background: green
}

layer.js (入口 核心)

import layerHtml from './layer.html'
import './layer.less'
function layer() {
  return {
    name: 'layer',
    template: layerHtml
  }
}

export { layer }

index.js (整個項目入口文件)

import { layer } from './components/layer/layer.js'
const App = function ()   {
  var app = document.getElementById('app')
  var layerHTML = layer().template
  app.innerHTML = layerHTML
}
App()

public/html:模版html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>webpack test</title>
</head>
<body>
  <div id="app"></div>
</body>
</html>

webpack.config.js

const path = require('path')
const htmlWebpackPlugin = require('html-webpack-plugin') // 引入插件
module.exports = {
  // css、js都是從入口文件開始 css、js都是通過import引入js
  entry: {
    index: './src/index.js'
  },
  output: {
    filename: 'js/[name].[chunkhash].js', // 在filename中也可以指定路徑
    path: path.join(__dirname, 'dist')
  },
  module: {
    rules: [{
      test: /\.js$/,
      loader: 'babel-loader',
      exclude: __dirname + 'node_modules',
      include: __dirname + 'src',
      options: {
        presets: ['env'] // 版本
      }
    }, {
      test: /\.css$/,
      loader: ['style-loader', 'css-loader'] // 從右向左,先執行css-loader再style-loader
    }, {
      test: /\.less$/,
      loader: ['style-loader', 'css-loader', 'less-loader']
    }, {
      test:/\.scss$/,
      loader: ['style-loader', 'css-loader', 'scss-loader']
    }, {
      test:/\.html$/,
      loader: ['html-loader']
    }]
  },
  plugins: [
    new htmlWebpackPlugin({
      template: 'public/index.html',
      filename: 'index.[chunkhash].html',
      chunks: ['index'],
      inject: 'true',
      minify: {
        removeComments: true, // 刪除註釋
        collapseWhitespace: true // 刪除空格
      }
    })
  ]
}

npm run build 打包!

找到dist文件夾下的html運行:

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章