We want to divide our large frontend projects into multiple separately deployed projects which are easier to work with. I am trying to include a bundled ngModule to handle a route from within another app. The apps must be ignorant of each other's configuration. The bundles will share some large dependencies(like Angular) via globals. We don't need to shake across the bundles and we may just have to accept some duplicate dependencies.
The root router complains that
Error: No NgModule metadata found for 'TestsetModule'.
which leads me to believe the child module is not being angular compiled on load, or is not registering its module for some reason. I think it may be necessary to manually compile the module, but I'm not sure how to use this https://angular.io/api/core/Compiler#compileModuleAndAllComponentsAsync
The root app loads the child via a route:
import { ModuleWithProviders } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
const load = require("little-loader");
const routes: Routes = [
{ path: ``, loadChildren: () => new Promise(function (resolve) {
load('http://localhost:3100/testset-module-bundle.js',(err: any) => {
console.log('global loaded bundle is: ', (<any>global).TestsetModule )
resolve((<any>global).TestsetModule)
}
)
})}
];
export const HostRouting: ModuleWithProviders = RouterModule.forRoot(routes);
I also tried using angular router's string resolution syntax rather than this weird global thing you see but I had similar issues.
Here is the module which is being loaded, very standard except for the global export:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { HttpModule } from '#angular/http';
//import { MaterialModule } from '#angular/material';
import { FlexLayoutModule } from '#angular/flex-layout';
import { FormsModule } from '#angular/forms';
import { LoggerModule, Level } from '#churro/ngx-log';
import { FeatureLoggerConfig } from './features/logger/services/feature-logger-config';
import { TestsetComponent } from './features/testset/testset.component';
import { TestsetRouting } from './testset.routing';
#NgModule({
imports: [
CommonModule,
//MaterialModule,
FlexLayoutModule,
HttpModule,
FormsModule,
LoggerModule.forChild({
moduleName: 'Testset',
minLevel: Level.INFO
}),
TestsetRouting,
],
declarations: [TestsetComponent],
providers: [
/* TODO: Providers go here */
]
})
class TestsetModule { }
(<any>global).TestsetModule = TestsetModule
export {TestsetModule as default, TestsetModule};
Here is the webpack configuration of the root bundle. Note the global exports via the poorly named "ProvidePlugin".
const webpack = require('webpack');
const AotPlugin = require('#ngtools/webpack').AotPlugin;
const path = require('path');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const IgnorePlugin = require('webpack/lib/IgnorePlugin');
const PolyfillsPlugin = require('webpack-polyfills-plugin');
const WebpackSystemRegister = require('webpack-system-register');
module.exports = (envOptions) => {
envOptions = envOptions || {};
const config = {
entry: {
'bundle': './root.ts'
},
output: {
libraryTarget: 'umd',
filename: '[name].js',//"bundle.[hash].js",
chunkFilename: '[name]-chunk.js',
path: __dirname
},
externals: {
},
resolve: {
extensions: ['.ts', '.js', '.html'],
},
module: {
rules: [
{ test: /\.html$/, loader: 'raw-loader' },
{ test: /\.css$/, loader: 'raw-loader' },
]
},
devtool: '#source-map',
plugins: [
new webpack.ProvidePlugin({
'angular': '#angular/core',
'ngrouter': '#angular/router',
'ngxlog':'#churro/ngx-log'
})
]
};
config.module.rules.push(
{ test: /\.ts$/, loaders: [
'awesome-typescript-loader',
'angular-router-loader',
'angular2-template-loader',
'source-map-loader'
] }
);
}
return config;
};
And here is the webpack configuration of the child bundle. Note the "externals" which look for angular as a global.
module.exports = (envOptions) => {
envOptions = envOptions || {};
const config = {
entry: {
'testset-module-bundle': './src/index.ts'
},
output: {
//library: 'TestsetModule',
libraryTarget: 'umd',
filename: '[name].js',//"bundle.[hash].js",
chunkFilename: '[name]-chunk.js',
path: path.resolve(__dirname, "dist")
},
externals: {
//expect these to come from the app that imported us
// name to be required : name from global
'angular': '#angular/core',
'ngrouter': '#angular/router',
'ngxlog': '#churro/ngx-log'
},
resolve: {
extensions: ['.ts', '.js', '.html'],
},
module: {
rules: [
{ test: /\.html$/, loader: 'raw-loader' },
{ test: /\.css$/, loader: 'raw-loader' },
]
},
devtool: '#source-map',
plugins: [
]
};
config.module.rules.push(
{ test: /\.ts$/, loaders: [
'awesome-typescript-loader',
'angular-router-loader',
'angular2-template-loader',
'source-map-loader'
] }
);
}
return config;
};
And for good measure here is my tsconfig file which 'awesome-typescript-loader' reads.
{
"compilerOptions": {
"target": "es5",
"module": "es2015",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true,
"baseUrl": ".",
"rootDir": "src",
"outDir": "app",
"paths": {
"#capone/*": [
"*"
],
"#angular/*": [
"node_modules/#angular/*"
],
"rxjs/*": [
"node_modules/rxjs/*"
]
}
},
"exclude": ["node_modules", "src/node_modules", "compiled", "src/dev_wrapper_app"],
"angularCompilerOptions": {
"genDir": "./compiled",
"skipMetadataEmit": true
}
}
If you're still reading, awesome. I was able to get this working when both bundles are part of the same webpack config and the child module is just a chunk. Angular is designed to do that. But our use case is to have the children and parent be ignorant of each other until runtime.
As you have mentioned
The apps must be ignorant of each other's configuration.
I had a similar problem in Angular2. I solved it by creating a sub-application. A separate sub-main.browser.ts and index.html file. It had its own dependencies, sharing the same node modules. Both main modules bootstrapping different app-component. We were working on Angular without angular-cli.
In webpack config, I added
entry: {
'polyfills': './src/polyfills.browser.ts',
'main' . : './src/main.browser.aot.ts',
'sub-main' : '/src/sub-main.browser.ts'
},
and a more detailed HtmlWebpackPlugin. In the chunks, we load only modules that will be used in both the app. If we see polyfills is common.
new HtmlWebpackPlugin({
template: 'src/index.html',
title: METADATA.title,
chunksSortMode: 'dependency',
metadata: METADATA,
inject: 'head',
chunks: ['polyfills','main']
}),
new HtmlWebpackPlugin({
template: 'src/index2.html',
title: 'Sub app',
chunksSortMode: 'dependency',
metadata: METADATA,
inject: 'head',
filename: './sub-app.html',
chunks: ['polyfills','sub-main']
}),
The next task was to create separate endpoints for both sub apps for dev environment.
devServer: {
port: METADATA.port,
host: METADATA.host,
historyApiFallback: true,
watchOptions: {
aggregateTimeout: 300,
poll: 1000
},
proxy: {
"/sub-app": {
target: "http://localhost:3009",
bypass: function(req, res, proxyOptions) {
return "/index2.html";
}
}
}
},
Now when I build the project two different HTML files are generated. Each with their own javascript bundle dependencies and common assets. They can be deployed on a different server as well.
I was able to finish my POC with lots of trial and error. My suggestion will be to look a step above angular. See how webpack is deploying your current project. And If you can configure it to serve your purpose.
Related
I've succesfully added vite to my project. It builds fine for prodiction. However in Production I have an error
Uncaught ReferenceError: describe is not defined
at index.ba9d79ff.js:1119:1426
I then saw the my .spec files where being added. I thought vite would of handled the removal of the test files. I want to remove my .spec files from production.
but not having such luck. I'm using Vue 2 with vite. I added
production: {
exclude: ['src/components/**/*.{spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}']
},
but the files are still being added. Is there something more I need to do?
My config
import { defineConfig } from "vite";
import { createVuePlugin as vue } from "vite-plugin-vue2";
import { VuetifyResolver } from "unplugin-vue-components/resolvers";
import Components from "unplugin-vue-components/vite";
// https://vitejs.dev/config/const
const path = require("path");
export default defineConfig({
plugins: [
vue(),
Components({
resolvers: [
// Vuetify
VuetifyResolver(),
],
}),
],
resolve: {
extensions: [
".mjs",
".js",
".ts",
".jsx",
".tsx",
".json",
".vue",
".scss",
],
alias: {
"#": path.resolve(__dirname, "./src"),
json2csv: "json2csv/dist/json2csv.umd.js",
"~bootstrap": "bootstrap",
},
},
production: {
exclude: ['src/components/**/*.{spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}']
},
extensions: etc,
css: {
preprocessorOptions: {
scss: {
// additionalData: `#import "src/scss/app.scss";`,
// additionalData: `#import "src/scss/_variables.scss";`,
sourceMap: false,
additionalData(source, fp) {
// All scss files ending with imports.scss
// will not re-import additionalData
if (fp.endsWith("_variables.scss")) return source;
// Use additionalData from legacy nuxt scss options
// return `#import "#/assets/mixin.scss"; ${source}`;
return `#import "src/scss/_variables.scss"; ${source}`;
},
},
},
},
server: {
port: 8090,
},
});
I have a component library written in vue that I am wrapping up with rollup
I am having an issue with mixins not being wrapped up into the final library. Intially i thought that the path was the issue as most of the mixins are local.
Originally:
import mixin from '../../mixins/color'
Repo folder structure
- dist //output
- src //All files related to the actual component within the library
- components
- comps
- alert //general components
- inputs //input components
- layout //layout components /row/col
- mixins
- utilities
- entry.js //rollup points to this
- ... //I used nuxt to develop the components to focus on SSR so there are more folders but are excluded in the rollup process
Apparently native rollup doesn't like indirect imports so I attempted to add rollup-plugin-includepaths. My understanding is that I would need to mention the paths required in the imports to work correctly.
Therefore, I added rollup-plugin-includepaths to rollup.config.js plugins and added the root path and the output director as the options
includePaths({
paths: ['src/components/', 'src/mixins/', 'src/utilities/'],
extensions: ['.js', '.vue']
}),
**this did not work **
I decided to remove all relative imports and create aliases for each required directory. This did not work either
What is happening is all mixins imported into the component and added as mixin: [mixins] //whatever they may be are not included in the compiled product?!?!?!
What am I missing????
// rollup.config.js
import fs from 'fs'
import path from 'path'
import vue from 'rollup-plugin-vue'
import alias from '#rollup/plugin-alias'
import commonjs from '#rollup/plugin-commonjs'
import replace from '#rollup/plugin-replace'
import babel from 'rollup-plugin-babel'
import { terser } from 'rollup-plugin-terser'
import minimist from 'minimist'
import postcss from 'rollup-plugin-postcss'
import includePaths from 'rollup-plugin-includepaths'
import del from 'rollup-plugin-delete'
// Get browserslist config and remove ie from es build targets
const esbrowserslist = fs
.readFileSync('./.browserslistrc')
.toString()
.split('\n')
.filter(entry => entry && entry.substring(0, 2) !== 'ie')
const argv = minimist(process.argv.slice(2))
const projectRoot = path.resolve(__dirname)
const baseConfig = {
input: 'src/entry.js',
plugins: {
preVue: [
alias({
resolve: ['.js', '.jsx', '.ts', '.tsx', '.vue'],
entries: [
{ find: '#', replacement: path.resolve(projectRoot, 'src') },
{
find: '#mixins',
replacement: path.resolve(projectRoot, 'src', 'mixins')
},
{
find: '#comps',
replacement: path.resolve(projectRoot, 'src', 'components', 'comps')
},
{
find: '#inputs',
replacement: path.resolve(
projectRoot,
'src',
'components',
'inputs'
)
},
{
find: '#utilities',
replacement: path.resolve(projectRoot, 'src', 'utilities')
}
]
}),
includePaths({
paths: ['src/components/', 'src/mixins/', 'src/utilities/'],
extensions: ['.js', '.vue']
}),
commonjs(),
postcss()
],
replace: {
'process.env.NODE_ENV': JSON.stringify('production'),
'process.env.ES_BUILD': JSON.stringify('false')
},
vue: {
css: false,
template: {
isProduction: true
}
},
babel: {
exclude: 'node_modules/**',
extensions: ['.js', '.jsx', '.ts', '.tsx', '.vue']
}
}
}
// ESM/UMD/IIFE shared settings: externals
// Refer to https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency
const external = [
// list external dependencies, exactly the way it is written in the import statement.
// eg. 'jquery'
'vue'
]
// UMD/IIFE shared settings: output.globals
// Refer to https://rollupjs.org/guide/en#output-globals for details
const globals = {
// Provide global variable names to replace your external imports
// eg. jquery: '$'
vue: 'Vue'
}
// Customize configs for individual targets
const buildFormats = []
if (!argv.format || argv.format === 'es') {
const esConfig = {
...baseConfig,
external,
output: {
compact: true,
file: 'dist/comps.esm.js',
format: 'esm',
exports: 'named'
},
plugins: [
del({ targets: 'dist/*' }),
replace({
...baseConfig.plugins.replace,
'process.env.ES_BUILD': JSON.stringify('true')
}),
...baseConfig.plugins.preVue,
vue(baseConfig.plugins.vue),
babel({
...baseConfig.plugins.babel,
presets: [
[
'#babel/preset-env',
{
targets: esbrowserslist
}
]
]
})
]
}
buildFormats.push(esConfig)
}
if (!argv.format || argv.format === 'cjs') {
const umdConfig = {
...baseConfig,
external,
output: {
compact: true,
file: 'dist/comps.ssr.js',
format: 'cjs',
name: 'Components',
exports: 'named',
globals
},
plugins: [
replace(baseConfig.plugins.replace),
...baseConfig.plugins.preVue,
vue({
...baseConfig.plugins.vue,
template: {
...baseConfig.plugins.vue.template,
optimizeSSR: true
}
}),
babel(baseConfig.plugins.babel)
]
}
buildFormats.push(umdConfig)
}
if (!argv.format || argv.format === 'iife') {
const unpkgConfig = {
...baseConfig,
external,
output: {
compact: true,
file: 'dist/comps.min.js',
format: 'iife',
name: 'Components',
exports: 'named',
globals
},
plugins: [
replace(baseConfig.plugins.replace),
...baseConfig.plugins.preVue,
vue(baseConfig.plugins.vue),
babel(baseConfig.plugins.babel),
terser({
output: {
ecma: 5
}
})
]
}
buildFormats.push(unpkgConfig)
}
// Export config
export default buildFormats
Update
I moved the imported components out of the mixin and added them directly to the component that included them and got the same result. Therefore, i really have no clue what needs to happen.
TL;DR
None of the child components are being included in the rolled up dist '.js' files
Sometimes it is hard to include what is relevant and the question above is guilty.
The problem is within the larger component I had imported the children lazily
ex:
components:{
comp: ()=>import('comp') ///Does not work
}
changed to your standard
import comp from 'comp'
components:{
comp
}
I'm new to aurelia and wanted to add a datepicker in my form, I saw this post from danyow, showing how to add datepicker using jquery. But would love to use a datepicker from bootstrap.
And so I saw this another post, haven't tried the second link because as I'm scanning the node_modules (if it matters, I use the spa templates found here), I saw a folder aurelia-bootstrap-datepicker and under the src folder, there's a aurelia-bootstrap-datepicker.js in which the content is pretty much the same with the second link.
Can I use that folder to have a datepicker? If yes, how? Or should I just follow the second link to create one myself?
What I tried:
use it as feature in my boot.ts file aurelia.use.standardConfiguration().feature(PLATFORM.moduleName('aurelia-bootstrap-datepicker'));
use it as a plugin
require it on my html file
Everything above, nothing is working for me.
Please advise. Thanks
EDIT:
boot.ts
import 'isomorphic-fetch';
import { Aurelia, PLATFORM } from 'aurelia-framework';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap';
declare const IS_DEV_BUILD: boolean; // The value is supplied by Webpack during the build
export function configure(aurelia: Aurelia) {
aurelia.use.standardConfiguration()
.plugin(PLATFORM.moduleName('aurelia-validation'));
if (IS_DEV_BUILD) {
aurelia.use.developmentLogging();
}
aurelia.start().then(() => aurelia.setRoot(PLATFORM.moduleName('app/components/app/app')));
}
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const { AureliaPlugin } = require('aurelia-webpack-plugin');
const bundleOutputDir = './wwwroot/dist';
module.exports = (env) => {
const isDevBuild = !(env && env.prod);
return [{
stats: { modules: false },
entry: { 'app': 'aurelia-bootstrapper' },
resolve: {
extensions: ['.ts', '.js'],
modules: ['ClientApp', 'node_modules'],
},
output: {
path: path.resolve(bundleOutputDir),
publicPath: '/dist/',
filename: '[name].js'
},
module: {
rules: [
{ test: /\.ts$/i, include: /ClientApp/, use: 'ts-loader?silent=true' },
{ test: /\.html$/i, use: 'html-loader' },
{ test: /\.css$/i, use: isDevBuild ? 'css-loader' : 'css-loader?minimize' },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
]
},
plugins: [
new webpack.DefinePlugin({ IS_DEV_BUILD: JSON.stringify(isDevBuild) }),
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
}),
new AureliaPlugin({ aureliaApp: 'boot' })
].concat(isDevBuild ? [
new webpack.SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(bundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
new webpack.optimize.UglifyJsPlugin()
])
}];
}
This is for the latest release of angular(rc4). I have been following the guide for using webpack with angular 2 provided here Angular 2 Webpack intro. No notable errors when packaging with webpack occur. A handful of warnings about dropping unused variables. The website does seem to bootstrap as many of my components load, but not all load correctly. I am receiving the following error
Uncaught ReferenceError: System is not defined
Along with many REST errors that don't make much of any sense. I am running the webpack-dev-server locally on port 8080, but I am not sure why it is trying to perform REST calls to it. I am making rest calls to another machine in some components but those are not being fired off.
POST http://localhost:8080/undefinedsession 404 (Not Found)
I have my webpack configured very similarly to the example in the angular doc. I am already using
"module": "commonjs",
in my tsconfig.json (as suggested here). Note that in my vendor.ts, I have commented out many references to systemjs modules. The example from the angular doc says they were removed in lieu of webpack. When I include them, I still see the system not defined error, along with additional errors
./~/systemjs/dist/system.src.js
Critical dependencies: 1642:42-49 require function is used in a way in
which dependencies cannot be statically extracted
Anyone else having this issue?
Here's my webpack.common.js:
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var helpers = require('./helpers');
var path = require('path');
module.exports = {
entry: {
'polyfills': './app/polyfills.ts',
'vendor': './app/vendor.ts',
'app': './app/main.ts'
},
resolve: {
extensions: ['', '.js', '.ts', '.config'],
root: [path.resolve('./')]
},
node: {
fs: "empty"
},
module: {
loaders: [
{
test: /\.ts$/,
loaders: ['ts', 'angular2-template-loader']
},
{
test: /\.html$/,
loader: 'html'
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: 'file?name=assets/[name].[hash].[ext]'
},
{
test: /\.config$/,
loader: 'file'
},
{
test: /\.css$/,
exclude: helpers.root('src', 'app'),
loader: ExtractTextPlugin.extract('style', 'css?sourceMap')
},
{
test: /\.css$/,
include: helpers.root('src', 'app'),
loader: 'raw'
}
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: ['app', 'vendor', 'polyfills']
}),
new HtmlWebpackPlugin({
template: 'index.html'
})
]
};
And here is the webpack.dev.js:
var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var helpers = require('./helpers');
module.exports = webpackMerge(commonConfig, {
devtool: 'cheap-module-eval-source-map',
output: {
path: helpers.root('dist'),
publicPath: 'http://localhost:8080/',
filename: '[name].js',
chunkFilename: '[id].chunk.js'
},
plugins: [
new ExtractTextPlugin('[name].css')
],
devServer: {
historyApiFallback: true,
stats: 'minimal'
}
});
Note that I have setup three entry files in line with the angular doc. Here are those for completeness
Main.ts:
import { bootstrap } from '#angular/platform-browser-dynamic';
import { HTTP_BINDINGS, HTTP_PROVIDERS } from '#angular/http';
import { disableDeprecatedForms, provideForms } from '#angular/forms';
import 'rxjs/Rx';
import { enableProdMode, provide, PLATFORM_DIRECTIVES } from '#angular/core';
import { ROUTER_DIRECTIVES } from '#angular/router';
import { Title } from '#angular/platform-browser';
import { AppComponent } from './app.component';
import { AppSettingsService } from './app.settings';
import { APP_ROUTER_PROVIDERS } from './app.routes';
// css
import 'css/material.blue_grey-blue.min.css';
import 'css/styles.css';
bootstrap(AppComponent, [
APP_ROUTER_PROVIDERS,
HTTP_BINDINGS,
HTTP_PROVIDERS,
Title,
AppSettingsService,
disableDeprecatedForms(),
provideForms(),
provide(PLATFORM_DIRECTIVES, { useValue: [ROUTER_DIRECTIVES], multi: true })
]).catch((err: any) => console.error(err));
polyfills.ts:
import 'core-js/es6';
import 'reflect-metadata';
require('zone.js/dist/zone');
if (process.env.ENV === 'production') {
// Production
} else {
// Development
Error['stackTraceLimit'] = Infinity;
require('zone.js/dist/long-stack-trace-zone');
}
vendor.ts:
// Angular 2
import '#angular/platform-browser';
import '#angular/platform-browser-dynamic';
import '#angular/core';
import '#angular/common';
import '#angular/http';
import '#angular/router';
// RxJS
import 'rxjs';
// From index.html
import 'js/material.js';
//import 'node_modules/core-js/client/shim.min.js';
//import 'node_modules/zone.js/dist/zone.js';
//import 'node_modules/reflect-metadata/Reflect.js';
//import 'node_modules/systemjs/dist/system.src.js';
//import 'systemjs.config.js';
I;m wondering if it's possible to build a bundle with some javascript files but without dependencies?
I want to have small bundles with React components (each react component in my case is builded from few react components, for example Comment component incldues comment box, list, and form),
I can split React components to a separate files by specifying few entry points in webpack, but if I have:
1. Component comment
2. Component newsletter
and both of them require ReactDOM, files which will be generated will have like 600kb, where my react components contain only ~100 lines of js code.
I would like to have one more file which will contain all the code which would come from "require('react-dom'), and those two files which will only have the React component code. is that possible?
My current setup:
'use strict';
import path from 'path';
import CommonsChunkPlugin from "webpack/lib/optimize/CommonsChunkPlugin";
module.exports = {
entry: {
app: "./app.js",
newsletter: "./components/renderers/newsletter.renderer.js",
comment: "./components/renderers/comment.renderer.js"
},
output: {
path: path.join(__dirname),
filename: "built/[name].entry.js"
},
devtool: 'sourcemaps',
cache: true,
debug: true,
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: [/(node_modules)/],
loader: 'babel'
}
],
resolve: {
extensions: ['', '.js', '.jsx']
}
},
plugins: [
new CommonsChunkPlugin({
name: "comment.js",
chunks: ["comment", "app"],
minChunks: 2
}),
new CommonsChunkPlugin({
name: "newsletter.js",
chunks: ["newsletter", "app"],
minChunks: 2
})
]
};
Comment.renderer.js:
import CommentBox from './../comment/commentBox';
ReactDOM.render(
<CommentBox/>,
document.getElementById("comment")
);
Newsletter.renderer.js:
import Newsletter from './../newsletter/newsletter';
ReactDOM.render(
<Newsletter/>,
document.getElementById("newsletter")
);
app.js:
'use strict';
import React from 'react';
import ReactDOM from 'react-dom';
import client from './lib/client';
Ok I've managed how to do that:
import path from 'path';
import CommonsChunkPlugin from "webpack/lib/optimize/CommonsChunkPlugin";
module.exports = {
entry: {
vendor: ["react","react-dom", "underscore"],
comment: "./components/renderers/comment.renderer.js",
newsletter: "./components/renderers/newsletter.renderer.js"
},
output: {
path: path.join(__dirname),
filename: "built/[name].bundle.js"
},
devtool: 'sourcemaps',
cache: true,
debug: true,
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: [/(node_modules)/],
loader: 'babel'
}
],
resolve: {
extensions: ['', '.js', '.jsx']
}
},
plugins: [
new CommonsChunkPlugin({
name: "vendor",
minChunks: Infinity
})
]
};
this part:
minChunks: Infinity
will ensure that code included in bundle "vendor" is not included in any other bundle. Thanks to this approach, comment and newsletter will contain only my React components.
I use following code in webpack.config.js to exclude the external dependencies from bundle.
module.exports = {
...
...
externals:{
"react": "React",
"react-dom": "ReactDOM"
},
...
...
}
I found this answer from this link
To complement #AnandShanbhag's answer, you can take all the dependencies from package.json and turn them into externals with a function:
module.exports = {
...
// put everything inside package.json dependencies as externals
externals: Object.keys(require('./package.json').dependencies)
.reduce(
function (acc, cur) {
acc[cur] = cur
return acc
},
new Object()
),
...
}