我的演示应用程序有两个按钮,需要在点击时加载新的车把模板。
var $ = require('jquery');
$(function(){
$('.js_hbs-1').on('click', function(){
var $button = $(this);
var initText = $button.text();
$button.text('Loading...');
require.ensure([], function(){
var template = require('handlebars!./test.hbs');
var html1 = template({'number': 10000});
$button.text(initText);
$('.append-here').html(html1);
});
});
$('.js_hbs-2').on('click', function(){
var $button = $(this);
var initText = $button.text();
$button.text('Loading...');
require.ensure([], function(){
var template = require('handlebars!./test2.hbs');
var html2 = template({'number': 20000})
$('.append-here').html(html2);
$button.text(initText);
});
});
});
除了编译文件的1行hbs文件大约250kb外,所有这一切都没问题。
我是webpack的新手,我知道你可以配置一些插件,但似乎都没有。
我的webpack配置文件
var webpack = require("webpack");
module.exports = {
context: __dirname + "/public/javascripts/",
entry: {
app: "./app",
},
output: {
path: __dirname + "/public/javascripts/dist",
filename: '[name].bundle.js',
chunkFilename: "[id].bundle.js",
publicPath: "../javascripts/dist/"
},
module: {
loaders: [
{ test: /\.hbs/, loader: "handlebars-template-loader" }
]
},
devtool: "#inline-source-map"
};
答案 0 :(得分:2)
我认为webpack做了一些疯狂的事情,但在vendor
条目中添加把手解决了我的问题。
结果配置:
var webpack = require("webpack");
module.exports = {
entry: {
app: __dirname + "/public/javascripts/app",
vendor: [
'backbone',
'handlebars'
],
},
output: {
path: __dirname + "/public/javascripts/dist",
filename: '[name].bundle.js',
chunkFilename: "[id].bundle.js",
publicPath: "../javascripts/dist/"
},
module: {
loaders: [
{ test: /\.hbs/, loader: "handlebars-template-loader" }
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: Infinity
}),
],
node: {
fs: "empty"
},
devtool: "#inline-source-map"
};
看起来上一段代码正常工作,但在添加此解决方案后文件大小增加了1MB:https://github.com/wycats/handlebars.js/issues/953#issuecomment-94931306
这也解决了这些警告: 警告在./~/handlebars/lib/index.js中 webpack不支持require.extensions。改为使用装载机。
WARNING in ./~/handlebars/lib/index.js
require.extensions is not supported by webpack. Use a loader instead.
WARNING in ./~/handlebars/lib/index.js
require.extensions is not supported by webpack. Use a loader instead.
var webpack = require("webpack");
var path = require('path');
module.exports = {
entry: {
app: __dirname + "/public/javascripts/app",
vendor: [
'backbone',
'handlebars'
],
},
output: {
path: __dirname + "/public/javascripts/dist",
filename: '[name].bundle.js',
chunkFilename: "[id].bundle.js",
publicPath: "../javascripts/dist/"
},
module: {
loaders: [
{ test: /\.hbs/, loader: "handlebars-template-loader" }
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: Infinity
}),
],
node: {
fs: "empty"
},
devtool: "#inline-source-map",
resolve: {
modulesDirectories: ['node_modules', 'src'],
fallback: path.join(__dirname, 'node_modules'),
alias: {
'handlebars': 'handlebars/runtime.js'
}
},
resolveLoader: {
fallback: path.join(__dirname, 'node_modules'),
alias: {
'hbs': 'handlebars-loader'
}
}
};