一、項目結構css
安裝loader:html
npm i html-loader --save-dev
npm i ejs-loader --save-dev
二、模板文件layer.tplnode
<div class="layer">
<div>this is <%= name %> layer</div>
<% for (var i = 0;i < arr.length; i++) { %>
<%= arr[i] %>
<% } %>
</div>
三、layer.jswebpack
import './layer.less'; //import tpl from './layer.html';
import tpl from './layer.tpl'; function Layer(){ return { name:'layer', tpl:tpl } } export default Layer;
四、app.jsweb
import './css/common.css'; import layer from './components/layer/layer.js' const App = function(){ var dom= document.getElementById('app'); var Layer = new layer(); dom.innerHTML = Layer.tpl({ name:'john', arr:['apple','xiaomi','oppo'] }); } new App()
注意:npm
Layer.tpl是函數。
五、webpack.config.jsbabel
var htmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/app.js', output: { path: __dirname + '/dist', filename: 'js/[name].js' }, module: { loaders: [{ test: /\.js$/, //如下目錄不處理
exclude: /node_modules/, //只處理如下目錄
include: /src/, loader: "babel-loader", //配置的目標運行環境(environment)自動啓用須要的 babel 插件
query: { presets: ['latest'] } }, //css 處理這一塊
{ test: /\.css$/, use: [ 'style-loader', { loader: 'css-loader', options: { //支持@important引入css
importLoaders: 1 } }, { loader: 'postcss-loader', options: { plugins: function() { return [ //必定要寫在require("autoprefixer")前面,不然require("autoprefixer")無效
require('postcss-import')(), require("autoprefixer")({ "browsers": ["Android >= 4.1", "iOS >= 7.0", "ie >= 8"] }) ] } } } ] }, //less 處理這一塊
{ test: /\.less$/, use: ['style-loader', { loader: 'css-loader', options: { //支持@important引入css
importLoaders: 1 } }, { loader: 'postcss-loader', options: { plugins: function() { return [ //必定要寫在require("autoprefixer")前面,不然require("autoprefixer")無效
require('postcss-import')(), require("autoprefixer")({ "browsers": ["Android >= 4.1", "iOS >= 7.0", "ie >= 8"] }) ] } } }, 'less-loader' ] }, //處理html模板
{ test: /\.html$/, use: { loader: 'html-loader' } }, //處理tpl模板
{ test: /\.tpl$/, loader: 'ejs-loader' }, ] }, plugins: [ new htmlWebpackPlugin({ template: 'index.html', filename: 'index.html' }) ] }
六、編譯app
npm run webpack
七、結果less