Webpack 4 - Migrating from CommonsChunkPlugin to SplitChunksPlugin - webpack-4

We have a traditional server rendered application (non SPA) where each page is augmented with vuejs
Our existing webpack 3 configuration is
webpack.config.js
var webpack = require('webpack')
var path = require('path')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
module.exports = {
entry: {
shared: './shared.js',
pageA: './pageA.js',
// pageB: './pageB.js',
// pageC: './pageC.js',
// etc
},
resolve: {
alias: { vue: 'vue/dist/vue.esm.js' },
},
output: {
path: path.join(__dirname, './dist'),
filename: '[name].js',
},
module: {
rules: [
{
test: /\.css$/,
exclude: /node_modules/,
use: ExtractTextPlugin.extract({
use: [
{
loader: 'css-loader',
query: {
sourceMap: true,
},
},
],
}),
},
],
},
plugins: [
new CleanWebpackPlugin('./dist'),
new webpack.optimize.CommonsChunkPlugin({
name: ['shared'],
minChunks: Infinity,
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'runtime',
}),
new ExtractTextPlugin('[name].css'),
new CopyWebpackPlugin([{ from: 'index.html', to: '.' }]),
],
}
shared.js
// import shared dependencies & pollyfills
var vue = require('vue')
// import global site css file
require('./shared.css')
// initialize global defaults
// vue.setDefaults(...)
console.log('shared', { vue })
pageA.js
var vue = require('vue')
// only this page uses axios
var axios = require('axios')
console.log('pageA', { vue, axios })
shared.css
body {
background-color: aquamarine;
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<!-- included on every page-->
<link rel="stylesheet" href="shared.css">
</head>
<body>
<!-- included on every page-->
<script src="runtime.js"></script>
<script src="shared.js"></script>
<script src="pageA.js"></script>
</body>
</html>
With this setup
1) runtime.js contains the webpack loader, so any changes to shared.js don't cause pageA.js to be cache busted and vice versa
2) shared.js contains any shared dependencies (in this case vue) as well as any shared global initializion for every page (setting vue defaults etc). It is also the point we import our shared global css file.
3) pageA.js does not contain any dependencies imported in shared.js (vue in this case) but does contain dependicies it imports (axios in this case).
We have been unable to reproduce this setup using the SplitChunksPlugin
1) SplitChunksPlugin doesn't seem to allow an entry point as a split point.
2) All the examples have split out ALL node module dependices into a vendor chunk. This doesn't work for us as we have 100's of pages but only a few import a graphing library or moment etc... We don't want to have this graphing library or moment included in shared.js as it will then be load for all pages.
3) It wasn't clear how to split the runtime into its own file either
SplitChunksPlugin seems to be targeted at SPA's where javascript can be loaded on demand. Is the scenario we are trageting still supported?

Are you trying to migrate to webpack 4?
I find the optimisation cacheGroups test option works well to be specific about what goes where.
optimization: {
splitChunks: {
cacheGroups: {
shared: {
test: /node_modules[\\/](?!axios)/,
name: "shared",
enforce: true,
chunks: "all"
}
}
}
}
Will load everything from the node modules (except axios) and should therefore be included as part of your page entry point.

If you want webpack to chunk some component, you will need to import it asynchronously from your main entry file.
I have been using bundle-loader to do it, then I have:
In my webpack.config.js
optimization: {
splitChunks: {
chunks: 'all'
},
mergeDuplicateChunks: true,
}
module: {
rules: [
{
test: /\.bundle\.js$/, //yes my output file contains the bundle in its name
use: {
loader: 'bundle-loader', options: {lazy: true}
}
}
]
}
In my entry file.
//this code will replace the line where you are importing this component
let Login;
// this method will go inside your component
componentWillMount() {
require("bundle-loader!./ui/Login.jsx")((loginFile) => {
Login = loginFile.default;
this.setState({ loginLoaded: true });
});
}
If you don't want to use it, there are more ways of importing your file async.

Related

How to share assets [css,images,...] in module federation with react

Basically I want to find a way to share example some css file or image using module federation in my case I want to use react.
I did some research by I don't find a solid information abou that.
Some recomendations ?
One solution that I found was using css-module, you can use webpack or browserify in any case your css will be transform in js and you can expose it and consume it like other object/component,...
Eg:
[ Home Content Component]
import styles from './exampleCss.module.scss'; // using css module
export const globalHomeStyle = styles; //exporting the new transformed js.
webpack.config.js
...
plugins: [
new ModuleFederationPlugin({
name: 'home',
filename: 'remoteEntry.js',
remotes: {
...
},
exposes: {
'./HomeContent': './src/HomeContent.jsx',
}
Consuming the style from Home microfrontend in PDP Microfrontend:
webpack.config.js //calling the microfrontend
...
plugins: [
new ModuleFederationPlugin({
name: 'home',
filename: 'remoteEntry.js',
remotes: {
home: 'home#http://localhost:3000/remoteEntry.js',
},
exposes: {
...
}
Using the Style in PDP Microfrontend:
import { globalHomeStyle } from 'home/HomeContent';
...rest implementation
<div className='flex'>
<div className={`font-bold text-3x1 flex-grow ${globalHomeStyle.exampleCss}`}>
I hope this can be useful, if you find other solutions don't be shy add them here 👍

Chunk files not calling/ loading in the browser

Trying to use reactjs + django webpack loader + webpack 4.
Everything builds perfectly main and other chunks files are generated successfully.
Unfortunately, page getting blank and its seems like corresponding chunk file is not calling/loading. only laoding main chunk. Is there anything missing in my webpack config?
'use strict';
const path = require('path');
const webpack = require('webpack');
const PnpWebpackPlugin = require('pnp-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent');
const getClientEnvironment = require('./config/env');
const paths = require('./config/paths');
const ManifestPlugin = require('webpack-manifest-plugin');
const getCacheIdentifier = require('react-dev-utils/getCacheIdentifier');
const ModuleNotFoundPlugin = require('react-dev-utils/ModuleNotFoundPlugin');
const BundleTracker = require('webpack-bundle-tracker');
// Webpack uses `publicPath` to determine where the app is being served from.
// In development, we always serve from the root. This makes config easier.
//const publicPath = '/';
const publicPath = '/static/rewards_bundles/';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_PATH%/xyz looks better than %PUBLIC_PATH%xyz.
const publicUrl = '';
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);
// style files regexes
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;
// common function to get style loaders
const getStyleLoaders = (cssOptions, preProcessor) => {
const loaders = [
require.resolve('style-loader'),
{
loader: require.resolve('css-loader'),
options: cssOptions,
},
{
// Options for PostCSS as we reference these options twice
// Adds vendor prefixing based on your specified browser support in
// package.json
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebook/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
require('postcss-preset-env')({
autoprefixer: {
flexbox: 'no-2009',
},
stage: 3,
}),
],
},
},
];
if (preProcessor) {
loaders.push(require.resolve(preProcessor));
}
return loaders;
};
// This is the development configuration.
// It is focused on developer experience and fast rebuilds.
// The production configuration is different and lives in a separate file.
module.exports = {
mode: 'development',
// You may want 'eval' instead if you prefer to see the compiled output in DevTools.
// See the discussion in https://github.com/facebook/create-react-app/issues/343
devtool: 'cheap-module-source-map',
// These are the "entry points" to our application.
// This means they will be the "root" imports that are included in JS bundle.
entry: [
// Include an alternative client for WebpackDevServer. A client's job is to
// connect to WebpackDevServer by a socket and get notified about changes.
// When you save a file, the client will either apply hot updates (in case
// of CSS changes), or refresh the page (in case of JS changes). When you
// make a syntax error, this client will display a syntax error overlay.
// Note: instead of the default WebpackDevServer client, we use a custom one
// to bring better experience for Create React App users. You can replace
// the line below with these two lines if you prefer the stock client:
// require.resolve('webpack-dev-server/client') + '?/',
// require.resolve('webpack/hot/dev-server'),
require.resolve('react-dev-utils/webpackHotDevClient'),
// Finally, this is your app's code:
paths.appIndexJs,
// We include the app code last so that if there is a runtime error during
// initialization, it doesn't blow up the WebpackDevServer client, and
// changing JS code would still trigger a refresh.
],
output: {
path: path.resolve('../../../rewards/app_static/rewards_bundles/'),
// Add /* filename */ comments to generated require()s in the output.
pathinfo: true,
// This does not produce a real file. It's just the virtual path that is
// served by WebpackDevServer in development. This is the JS bundle
// containing code from all our entry points, and the Webpack runtime.
filename: 'static/js/bundle.js',
// There are also additional JS chunk files if you use code splitting.
chunkFilename: 'static/js/[name].chunk.js',
// This is the URL that app is served from. We use "/" in development.
publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: info =>
path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
},
optimization: {
// Automatically split vendor and commons
// https://twitter.com/wSokra/status/969633336732905474
// https://medium.com/webpack/webpack-4-code-splitting-chunk-graph-and-the-splitchunks-optimization-be739a861366
splitChunks: {
chunks: 'all',
name: false,
},
// Keep the runtime chunk seperated to enable long term caching
// https://twitter.com/wSokra/status/969679223278505985
runtimeChunk: true,
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebook/create-react-app/issues/253
modules: ['node_modules'].concat(
// It is guaranteed to exist because we tweak it in `env.js`
process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebook/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: ['.web.js', '.js', '.json', '.web.jsx', '.jsx'],
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
},
plugins: [
// Adds support for installing with Plug'n'Play, leading to faster installs and adding
// guards against forgotten dependencies and such.
PnpWebpackPlugin,
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
],
},
resolveLoader: {
plugins: [
// Also related to Plug'n'Play, but this time it tells Webpack to load its loaders
// from the current package.
PnpWebpackPlugin.moduleLoader(module),
],
},
module: {
strictExportPresence: true,
rules: [
// Disable require.ensure as it's not a standard language feature.
{ parser: { requireEnsure: false } },
// First, run the linter.
// It's important to do this before Babel processes the JS.
{
test: /\.(js|jsx)$/,
enforce: 'pre',
use: [
{
options: {
formatter: require.resolve('react-dev-utils/eslintFormatter'),
eslintPath: require.resolve('eslint'),
},
loader: require.resolve('eslint-loader'),
},
],
include: paths.appSrc,
},
{
// `mjs` support is still in its infancy in the ecosystem, so we don't
// support it.
// Modules who define their `browser` or `module` key as `mjs` force
// the use of this extension, so we need to tell webpack to fall back
// to auto mode (ES Module interop, allows ESM to import CommonJS).
test: /\.mjs$/,
include: /node_modules/,
type: 'javascript/auto',
},
{
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
// "url" loader works like "file" loader except that it embeds assets
// smaller than specified limit in bytes as data URLs to avoid requests.
// A missing `test` is equivalent to a match.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]',
},
},
// Process application JS with Babel.
// The preset includes JSX, Flow, and some ESnext features.
{
test: /\.(js|jsx)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
customize: require.resolve(
'babel-preset-react-app/webpack-overrides'
),
plugins: [
[
require.resolve('babel-plugin-named-asset-import'),
{
loaderMap: {
svg: {
ReactComponent: '#svgr/webpack?-prettier,-svgo![path]',
},
},
},
],
],
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true,
// Don't waste time on Gzipping the cache
cacheCompression: false,
},
},
// Process any JS outside of the app with Babel.
// Unlike the application JS, we only compile the standard ES features.
{
test: /\.js$/,
exclude: /#babel(?:\/|\\{1,2})runtime/,
loader: require.resolve('babel-loader'),
options: {
babelrc: false,
configFile: false,
compact: false,
presets: [
[
require.resolve('babel-preset-react-app/dependencies'),
{ helpers: true },
],
],
cacheDirectory: true,
// Don't waste time on Gzipping the cache
cacheCompression: false,
// If an error happens in a package, it's possible to be
// because it was compiled. Thus, we don't want the browser
// debugger to show the original code. Instead, the code
// being evaluated would be much more helpful.
sourceMaps: false,
},
},
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use a plugin to extract that CSS to a file, but
// in development "style" loader enables hot editing of CSS.
// By default we support CSS Modules with the extension .module.css
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
}),
},
// Adds support for CSS Modules (https://github.com/css-modules/css-modules)
// using the extension .module.css
{
test: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
modules: true,
getLocalIdent: getCSSModuleLocalIdent,
}),
},
// Opt-in support for SASS (using .scss or .sass extensions).
// Chains the sass-loader with the css-loader and the style-loader
// to immediately apply all styles to the DOM.
// By default we support SASS Modules with the
// extensions .module.scss or .module.sass
{
test: sassRegex,
exclude: sassModuleRegex,
use: getStyleLoaders({ importLoaders: 2 }, 'sass-loader'),
},
// Adds support for CSS Modules, but using SASS
// using the extension .module.scss or .module.sass
{
test: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 2,
modules: true,
getLocalIdent: getCSSModuleLocalIdent,
},
'sass-loader'
),
},
// "file" loader makes sure those assets get served by WebpackDevServer.
// When you `import` an asset, you get its (virtual) filename.
// In production, they would get copied to the `build` folder.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
// Exclude `js` files to keep "css" loader working as it injects
// its runtime that would otherwise be processed through "file" loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/\.(js|jsx)$/, /\.html$/, /\.json$/],
loader: require.resolve('file-loader'),
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
],
},
// ** STOP ** Are you adding a new loader?
// Make sure to add the new loader(s) before the "file" loader.
],
},
plugins: [
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin({
inject: true,
template: paths.appHtml,
}),
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In development, this will be an empty string.
new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
// This gives some necessary context to module not found errors, such as
// the requesting resource.
new ModuleNotFoundPlugin(paths.appPath),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'development') { ... }. See `./env.js`.
new webpack.DefinePlugin(env.stringified),
// This is necessary to emit hot updates (currently CSS only):
new webpack.HotModuleReplacementPlugin(),
// Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this.
// See https://github.com/facebook/create-react-app/issues/240
new CaseSensitivePathsPlugin(),
// If you require a missing module and then `npm install` it, you still have
// to restart the development server for Webpack to discover it. This plugin
// makes the discovery automatic so you don't have to restart.
// See https://github.com/facebook/create-react-app/issues/186
new WatchMissingNodeModulesPlugin(paths.appNodeModules),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how Webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
// Generate a manifest file which contains a mapping of all asset filenames
// to their corresponding output file so that tools can pick it up without
// having to parse `index.html`.
/*new ManifestPlugin({
fileName: '../../webpack-iso-rewards.json',
publicPath: publicPath,
}),*/
new BundleTracker({filename: '../../../rewards/webpack-iso-rewards.json'}),
],
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty',
},
// Turn off performance processing because we utilize
// our own hints via the FileSizeReporter
performance: false,
};
Please help!

Changing assets outputPath doesn't update in html

I'm trying to change the outputPaths for my assets from the default assets to media so I can more easily integrate it with my php framework.
In my ember-cli-build.js file, I've made the following modifications to my app as defined here:
var app = new EmberApp(defaults, {
fingerprint : {
replaceExtensions : [ 'html', 'php', 'css', 'js' ]
},
outputPaths: {
app: {
css: {
'app': '/media/application-name.css'
},
js: '/media/application-name.js'
},
vendor: {
css: '/media/vendor.css',
js: '/media/vendor.js'
}
},
'ember-power-select': {
theme: 'bootstrap'
}
});
While the generated application-name.css, application-name.js, vendor.css and vendor.js files are saved on the hard drive in the correct assets directory, the index.html file is not updated to match. Instead, it links to the same default assets/application-name.*s[s] files.
Any ideas why this isn't working? Thanks.
For fingerprinting to work, the path and file names in your index.html file and in your config.js file have to match. For example, if you have the below in your config file:
outputPaths: {
app: {
css: {
'app': '/media/my-application.css'
},
js: '/media/my-application.js'
},
vendor: {
css: '/media/vendor.css',
js: '/media/vendor.js'
}
}
You'll need to edit your index.html file to match:
<link rel="stylesheet" href="media/my-application.css">
<script src="media/my-application.js"></script>

Mocha test of React component which uses System.js to handle css import

How can I make mocha run with System.js handling all require/import statements? I have a React component which does an import of CSS file. When running on browser System.js gets loaded and it's plugin-css handles import of css files. But when running as a Mocha unit test import of a css file causes Mocha to crash.
import '../../../dist/css/common/NavBar.css!';
throws error
Error: Cannot find module '../../../dist/css/common/NavBar.css!'
Does anyone have a similar test setup up and running ?
You're probably gonna need to start using Karma and a plugin for System.js
https://www.npmjs.com/package/karma-systemjs
Here's a karma.conf.js to get you started:
module.exports = function(config) {
config.set({
browsers: [ 'Chrome' ],
singleRun: false,
frameworks: ['mocha', 'sinon', 'systemjs'],
plugins: [
'karma-systemjs'
'karma-chrome-launcher',
'karma-chai',
'karma-mocha',
'karma-sourcemap-loader',
'karma-spec-reporter',
'karma-mocha-reporter',
'karma-sinon'
],
files: [
'test/bootstrap.js'
],
reporters: [ 'spec' ],
systemjs: {
// Path to your SystemJS configuration file
configFile: 'app/system.conf.js',
// Patterns for files that you want Karma to make available, but not loaded until a module requests them. eg. Third-party libraries.
serveFiles: [
'lib/**/*.js'
],
// SystemJS configuration specifically for tests, added after your config file.
// Good for adding test libraries and mock modules
config: {
paths: {
'angular-mocks': 'bower_components/angular-mocks/angular-mocks.js'
}
}
}
});
};
and in test/bootstrap.js perhaps this:
//test/bootstrap.js
//put this in your test directory (include it with your tests or test recursively)
// setup globals
chai = require('chai');
chai.should();
chai.use(require('chai-things'));
assert = require('chai').assert;
expect = require('chai').expect;
should = require('chai').should;
React = require('react/addons');
global.TestUtils = React.addons.TestUtils;
ReactTools = require('react-tools');
reactStub = React.createClass({
displayName: 'StubClass',
mixins: [],
render: function() {
return null;
}
});
// setup
before(function(){
});
beforeEach(function(){
});
// teardown
afterEach(function() {
});
after(function(){
});
// include all the tests
var context = require.context('./', true, /-test\.js$/);
context.keys().forEach(context);
I got it working in nodejs itself. I just had to stub out imports to css files. Rest of stuff babel handles. This is my require file which mocha uses.
process.env.BABEL_DISABLE_CACHE = 1;
require('babel-core/register')({
'optional': [
'es7.classProperties'
],
'resolveModuleSource': function (source) {
if (source.indexOf('dist/css') !== -1) {
return '../../../test/css-dummy.js';
}
return source;
},
'blacklist': []
});

Ember 1.10+grunt+EAK: "Could not find <template_name> template or view" after migration from 1.9.1

I'm using Ember App Kit with grunt and I'm trying to switch to Ember 1.10 and can't get HTMLBars working :/
TL;DR
After migration, I've got my HTMLBars templates lodaded in Ember.TEMPLATES but they're not visible either by Ember nor in App.__container.lookup.cache.
Details
The steps I did:
updated ember and ember-data
updated package.json ("grunt-ember-templates": "0.5.0")
updated my Gruntfile.js (grunt.loadNpmTasks('grunt-ember-templates') added a task emberTemplates)
passed the options to emberTemplates:
{
debug: [],
options: {
templateCompilerPath: 'vendor/ember/ember-template-compiler.js',
handlebarsPath: 'vendor/handlebars/handlebars.js',
templateNamespace: 'HTMLBars'
},
'public/assets/templates.js': [
'app/templates/**/*.hbs'
],
};
removed handlebars.js from index.html and replaced ember.js with ember.debug.js
Now, I've got my public/assets/templates.js file generated in a proper way, I had several compilation errors coming from ember-template-compiler, so this part, I assume, is working fine.
Lastly, in the app, I can see all my templates loaded in Ember.TEMPLATES variable but unfortunately, they're not accessible from App.__container__.lookup.cache or App.__container__.lookup('template:<template_name>').
The way I'm trying to render the template that throws an error is (and it's working with Ember 1.9):
export default AuthRoute.extend({
renderTemplate: function() {
this.render();
this.render('user-details', {
into: 'base',
outlet: 'profile',
controller: 'user-details'
});
}
});
What am I missing? Any help would be appreciated.
Bonus question: what is debug field in emberTemplates configuration? If I don't define it, it raises an error (Required config property "emberTemplates.debug" missing.) while compiling. Could that be a possible reason?
Bonus question 2: where should templates.js file go? The intuition tells me /tmp but then, even Ember.TEMPLATES is an empty object...
EDIT [SOLUTION]:
I missed templateBasePath: "app/templates" line in the emberTemplates options. Because of that, Ember.TEMPLATES object was sth similar to this:
{
"app/templates/base.hbs": {},
"app/templates/components/component.hbs": {}
}
instead of:
{
"base.hbs": {},
"components/component.hbs": {}
}
which is the format that Ember resolver (ember-application/system/resolver) in the resolveTemplate method expects.
EDIT: using grunt-ember-templates and this Gruntfile task, I got it working:
emberTemplates: {
options: {
precompile: true,
templateBasePath: "templates",
handlebarsPath: "node_modules/handlebars/dist/handlebars.js",
templateCompilerPath: "bower_components/ember/ember-template-compiler.js"
},
"dist/js/templates.js": ["templates/**/*.hbs"]
}
Differences seem to be precompile: true and point the handlebarsPath to the dependency in node_modules. Also the templateBasePath makes the ids like application instead of templates/application. Or in your case app/templates/application.
To answer your Bonus question 2, put templates.js after you load ember.js but before your app.js. Mine script includes look like this:
<script type="text/javascript" src="/bower_components/ember/ember.debug.js"></script>
<script type="text/javascript" src="/bower_components/ember/ember-template-compiler.js"></script>
<script type="text/javascript" src="/js/templates.js"></script>
<script type="text/javascript" src="/js/app.js"></script>
====================================
EDIT: Ignore this newbness...
It seems like the grunt-ember-templates task is outdated, or its dependencies are outdated. Remove it. I was able to hack together this solution:
Use grunt-contrib-concat instead. The money is with the process option.
concat: {
dist: {
// other concat tasks...
},
templates: {
options: {
banner: '',
process: function(src, filepath) {
var name = filepath.replace('app/templates/','').replace('.hbs','');
var Map = {
10: "n",
13: "r",
39: "'",
34: '"',
92: "\\"
};
src = '"' + src.replace(/[\n\r\"\\]/g, function(m) {
return "\\" + Map[m.charCodeAt(0)]
}) + '"';
return 'Ember.TEMPLATES["'+name+'"] = Ember.HTMLBars.template(Ember.HTMLBars.compile('+src+'));\n';
}
},
files: {
'public/assets/templates.js': 'app/templates/**/*.hbs'
}
}
},
So the whole solution is as follows:
module.exports = {
debug: {
src: "app/templates/**/*.{hbs,hjs,handlebars}",
dest: "tmp/result/assets/templates.js"
},
dist: {
src: "<%= emberTemplates.debug.src %>",
dest: "<%= emberTemplates.debug.dest %>"
},
options: {
templateCompilerPath: 'vendor/ember/ember-template-compiler.js',
handlebarsPath: 'vendor/handlebars/handlebars.js',
templateNamespace: 'HTMLBars',
templateBasePath: "app/templates"
}
};
where all my templates reside in app/templates/ directory.
I'm still using:
<script src="/assets/templates.js"></script>
in index.html.
Maybe somebody will find it useful ;)