auto/manual init w/ single bundle, BYO root element 🎉 (#1173)

* ensure that application is only initialized once

* allow for single bundle init

* enable manual initialization via global flag
This commit is contained in:
Shawn Erquhart 2018-03-28 15:52:57 -04:00 committed by GitHub
parent 085c88e2b8
commit a19bc04c00
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 49 additions and 30 deletions

27
src/bootstrap.js vendored
View File

@ -13,8 +13,9 @@ import 'EditorWidgets';
import 'MarkdownPlugins'; import 'MarkdownPlugins';
import './index.css'; import './index.css';
function bootstrap(opts = {}) { const ROOT_ID = 'nc-root';
function bootstrap(opts = {}) {
const { config } = opts; const { config } = opts;
/** /**
@ -23,11 +24,25 @@ function bootstrap(opts = {}) {
console.log(`Netlify CMS version ${NETLIFY_CMS_VERSION}`); console.log(`Netlify CMS version ${NETLIFY_CMS_VERSION}`);
/** /**
* Create mount element dynamically. * Get DOM element where app will mount.
*/ */
const el = document.createElement('div'); function getRoot() {
el.id = 'nc-root'; /**
document.body.appendChild(el); * Return existing root if found.
*/
const existingRoot = document.getElementById(ROOT_ID);
if (existingRoot) {
return existingRoot;
}
/**
* If no existing root, create and return a new root.
*/
const newRoot = document.createElement('div');
newRoot.id = ROOT_ID;
document.body.appendChild(newRoot);
return newRoot;
}
/** /**
* Configure Redux store. * Configure Redux store.
@ -64,7 +79,7 @@ function bootstrap(opts = {}) {
/** /**
* Render application root. * Render application root.
*/ */
render(<Root />, el); render(<Root />, getRoot());
} }
export default bootstrap; export default bootstrap;

View File

@ -1,28 +1,25 @@
/**
* This module provides a self-initializing CMS instance with API hooks added to
* the `window` object.
*/
import React from 'react'; import React from 'react';
import bootstrap from './bootstrap'; import bootstrap from './bootstrap';
import registry from 'Lib/registry'; import registry from 'Lib/registry';
import createReactClass from 'create-react-class'; import createReactClass from 'create-react-class';
/** /**
* Load the app. * Load Netlify CMS automatically if `window.CMS_MANUAL_INIT` is set.
*/ */
if (!window.CMS_MANUAL_INIT) {
bootstrap(); bootstrap();
} else {
console.log('`window.CMS_MANUAL_INIT` flag set, skipping automatic initialization.');
}
/** /**
* Add extension hooks to global scope. * Add extension hooks to global scope.
*/ */
const CMS = { ...registry };
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
window.CMS = CMS; window.CMS = registry;
window.initCMS = bootstrap;
window.createClass = window.createClass || createReactClass; window.createClass = window.createClass || createReactClass;
window.h = window.h || React.createElement; window.h = window.h || React.createElement;
} }
/** export { registry as default, bootstrap as init };
* Export the registry for projects that import the CMS.
*/
export default CMS;

View File

@ -1,7 +0,0 @@
/**
* This module provides manual initialization and registry hooks.
*/
import bootstrap from './bootstrap';
import registry from 'Lib/registry';
export { bootstrap as init, registry };

View File

@ -13,7 +13,6 @@ module.exports = merge.smart(require('./webpack.base.js'), {
`webpack-dev-server/client?http://${ HOST }:${ PORT }/`, `webpack-dev-server/client?http://${ HOST }:${ PORT }/`,
'./index', './index',
], ],
init: './init',
}, },
output: { output: {
path: path.join(__dirname, 'dist'), path: path.join(__dirname, 'dist'),

View File

@ -8,7 +8,6 @@ const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = merge.smart(require('./webpack.base.js'), { module.exports = merge.smart(require('./webpack.base.js'), {
entry: { entry: {
cms: './index', cms: './index',
init: './init',
}, },
output: { output: {
path: path.join(__dirname, 'dist'), path: path.join(__dirname, 'dist'),

View File

@ -7,15 +7,31 @@ We run new functionality in an open beta format from time to time. That means th
**Use these features at your own risk.** **Use these features at your own risk.**
## Custom Mount Element
Netlify CMS always creates it's own DOM element for mounting the application, which means it always
takes over the entire page, and is generally inflexible if you're trying to do something creative,
like injecting it into a shared context.
You can now provide your own element for Netlify CMS to mount in by setting the target element's ID
as `nc-root`. If Netlify CMS finds an element with this ID during initialization, it will mount
within that element instead of creating it's own.
## Manual Initialization ## Manual Initialization
Netlify CMS can now be manually initialized, rather than automatically loading up the moment you import it. The whole point of this at the moment is to inject configuration into Netlify CMS before it loads, bypassing need for an actual config.yml. This is important, for example, when creating tight integrations with static site generators. Netlify CMS can now be manually initialized, rather than automatically loading up the moment you import it. The whole point of this at the moment is to inject configuration into Netlify CMS before it loads, bypassing need for an actual config.yml. This is important, for example, when creating tight integrations with static site generators.
Injecting config is technically already possible by setting `window.CMS_CONFIG` before importing/requiring/running Netlify CMS, but most projects are modular and don't want to use globals, plus `window.CMS_CONFIG` is an internal, not technically supported, and provides no validation. Therefore, we'll focus on manual initialization via the npm package. Injecting config is technically already possible by setting `window.CMS_CONFIG` before importing/requiring/running Netlify CMS, but most projects are modular and don't want to use globals, plus `window.CMS_CONFIG` is an internal, not technically supported, and provides no validation.
Assuming you have the netlify-cms package installed to your project, manual initialization works like so: Assuming you have the netlify-cms package installed to your project, manual initialization works like so:
```js ```js
import { init, registry } from 'netlify-cms/dist/init' // This global flag enables manual initialization.
window.CMS_MANUAL_INIT = true
// Usage with import from npm package
import CMS, { init } from 'netlify-cms'
// Usage with script tag
const { CMS, initCMS: init } = window
/** /**
* Initialize without passing in config - equivalent to just importing * Initialize without passing in config - equivalent to just importing
@ -44,7 +60,7 @@ init({
}) })
// The registry works as expected, and can be used before or after init. // The registry works as expected, and can be used before or after init.
registry.registerPreviewTemplate(...); CMS.registerPreviewTemplate(...);
``` ```
## Raw CSS in `registerPreviewStyle` ## Raw CSS in `registerPreviewStyle`