Local JavaScript Files Not Updating - Stencil CLI - javascript

I am modifying a purchased stencil-based theme for a client. When I modify javascript files, bundle.js does not update and I do not see a file change in the CLI. I am unable to see my changes on the local site. However, as a test, I was able to modify bundle.js directly and saw my change take place.
I have looked through the BC docs and have asked questions in other forums, but still no solution. I am not getting any errors in the CLI when I start stencil or run the bundle command. I can also upload my theme to the store without error.
Any ideas?
**Edit:
Here are the contents of my stencil.conf.js file:
var path = require('path');
var webpack = require('webpack');
var webpackConfig = require('./webpack.conf.js');
webpackConfig.context = __dirname;
webpackConfig.entry = path.resolve(__dirname, 'assets/js/app.js');
webpackConfig.output = {
path: path.resolve(__dirname, 'assets/js'),
filename: 'bundle.js'
};
/**
* Watch options for the core watcher
* #type {{files: string[], ignored: string[]}}
*/
var watchOptions = {
// If files in these directories change, reload the page.
files: [
'/assets',
'/templates',
'/lang'
],
//Do not watch files in these directories
ignored: [
'/assets/scss',
'/assets/css',
]
};
/**
* Hook into the stencil-cli browsersync instance for rapid development of themes.
* Watch any custom files and trigger a rebuild
* #param {Object} Bs
*/
function development(Bs) {
var compiler = webpack(webpackConfig);
// Rebuild the bundle once at bootup
compiler.watch({}, function(err, stats) {
if (err) {
console.error(err)
}
Bs.reload();
});
}
/**
*/
/**
* Hook into the `stencil bundle` command and build your files before they are packaged as a .zip
* Be sure to call the `done()` callback when finished
* #param {function} done
*/
function production(done) {
var compiler;
webpackConfig.devtool = false;
webpackConfig.plugins.push(new webpack.optimize.DedupePlugin());
webpackConfig.plugins.push(new webpack.optimize.UglifyJsPlugin({
comments: false
}));
compiler = webpack(webpackConfig);
compiler.run(function(err, stats) {
if (err) {
throw err;
}
done();
});
}
module.exports = {
watchOptions: watchOptions,
development: development,
production: production,
};
Here are the contents of my webpack.conf.js file:
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'eval-cheap-module-source-map',
bail: false,
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
include: [
path.resolve(__dirname, 'assets/js'),
path.resolve(__dirname, 'node_modules/#bigcommerce/stencil-utils'),
],
query: {
compact: false,
cacheDirectory: true,
presets: [ ['es2015', {loose: true}] ]
}
}
]
},
plugins: [],
watch: false
};

Related

Compiling a typescript project with webpack

I have a question for you - how is it possible to implement multi-file compilation while preserving the tree of folders and documents, while not writing each file into entry in this way
entry: {
index:'./src/index.ts',
'bot/main':'./src/bot/main.ts'
}
But at the same time, the files had their names and their position, as before compilation in js, only instead of the src folder, they were in the dist folder?
My current config webpack.config.js
const path = require('path')
const nodeExternals = require('webpack-node-externals')
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin')
module.exports = {
context: __dirname,
entry: {
index:'./src/index.ts',
'bot/main':'./src/bot/main.ts'
},
externals: [nodeExternals()],
module: {
rules: [
{
exclude: /node_modules/,
test: /.ts$/,
use: {
loader: 'ts-loader'
}
}
]
},
node: {
__dirname: false
},
resolve: {
extensions: ['.ts', '.js'],
plugins: [
new TsconfigPathsPlugin({
baseUrl: './src'
})
]
},
output: {
filename: '[name]js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/dist/'
},
target: 'node'
}
And when building in production mode, all this was compiled into one file, taking into account all URLs, imports, etc.
Is it even possible?
Webpack itself won't do that for you. You will need to write litter helper function to achieve this. The basic idea is to crawl the directory, find all the files and then provide them to Webpack:
const path = require('path');
const glob = require('glob');
const extension = 'ts';
// Recursively find all the `.ts` files inside src folder.
const matchedFiles = glob.sync(`./src/**/*.${extension}`, {
nodir: true
});
const entry = {};
matchedFiles.forEach((file) => {
const SRC_FOLDER = path.join(__dirname, 'src');
const ABS_PATH = path.join(__dirname, file);
// Generates relative file paths like `src/test/file.ts`
const relativeFile = path.relative(SRC_FOLDER, ABS_PATH);
// fileKey is relative filename without extension.
// E.g. `src/test/file.ts` becomes `src/test/file`
const fileKey = path.join(path.dirname(relativeFile), path.basename(relativeFile, extension));
entry[fileKey] = relativeFile;
});
module.exports = {
context: __dirname,
// Use the entry object generated above.
entry,
// ... rest of the configuration
};

Webpack DllPlugin with gulp: Cannot find module '... vendor-manifest.json'

I have a rather large React application built with webpack 2. The application is embedded into a Drupal site as a SPA within the existing site. The Drupal site has a complex gulp build setup and I can't replicate it with webpack, so I decided to keep it.
I have split my React application into multiple parts using the DllPlugin / DllReferencePlugin combo which is shipped out of the box in webpack 2. This works great, and I get a nice vendor-bundle when building with webpack.
The problem is when I try to run my webpack configuration in gulp, I get an error. I might be doing it wrong, as I have not been able to find much documentation on this approach, but nevertheless, it's not working for me.
It looks like it's trying to include the the manifest file from my vendor-bundle before creating it.
Whenever I run one of my defined gulp tasks, like gulp react-vendor I get an error, saying that it cannot resolve the vendor-manifest.json file.
If I on other hand run webpack --config=webpack.dll.js in my terminal, webpack compiles just fine and with no errors.
I have included what I think is the relevant files. Any help on this is appreciated.
webpack.config.js
// Use node.js built-in path module to avoid path issues across platforms.
const path = require('path');
const webpack = require('webpack');
// Set environment variable.
const production = process.env.NODE_ENV === "production";
const appSource = path.join(__dirname, 'react/src/');
const buildPath = path.join(__dirname, 'react/build/');
const ReactConfig = {
entry: [
'./react/src/index.jsx'
],
output: {
path: buildPath,
publicPath: buildPath,
filename: 'app.js'
},
module: {
rules: [
{
exclude: /(node_modules)/,
use: {
loader: "babel-loader?cacheDirectory=true",
options: {
presets: ["react", "es2015", "stage-0"]
},
},
},
],
},
resolve: {
modules: [
path.join(__dirname, 'node_modules'),
'./react/src/'
],
extensions: ['.js', '.jsx', '.es6'],
},
context: __dirname,
devServer: {
historyApiFallback: true,
contentBase: appSource
},
// TODO: Split plugins based on prod and dev builds.
plugins: [
new webpack.DllReferencePlugin({
context: path.join(__dirname, "react", "src"),
manifest: require(path.join(__dirname, "react", "vendors", "vendor-manifest.json"))
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
filename: 'webpack-loader.js'
}),
]
};
// Add environment specific configuration.
if (production) {
ReactConfig.plugins.push(
new webpack.optimize.UglifyJsPlugin()
);
}
module.exports = [ReactConfig];
webpack.dll.js
const path = require("path");
const webpack = require("webpack");
const production = process.env.NODE_ENV === "production";
const DllConfig = {
entry: {
vendor: [path.join(__dirname, "react", "vendors", "vendors.js")]
},
output: {
path: path.join(__dirname, "react", "vendors"),
filename: "dll.[name].js",
library: "[name]"
},
plugins: [
new webpack.DllPlugin({
path: path.join(__dirname, "react", "vendors", "[name]-manifest.json"),
name: "[name]",
context: path.resolve(__dirname, "react", "src")
}),
// Resolve warning message related to the 'fetch' node_module.
new webpack.IgnorePlugin(/\/iconv-loader$/),
],
resolve: {
modules: [
path.join(__dirname, 'node_modules'),
],
extensions: ['.js', '.jsx', '.es6'],
},
// Added to resolve a dependency issue in this build #https://github.com/hapijs/joi/issues/665
node: {
net: 'empty',
tls: 'empty',
dns: 'empty'
}
};
if (production) {
DllConfig.plugins.push(
new webpack.optimize.UglifyJsPlugin()
);
}
module.exports = [DllConfig];
vendors.js (to determine what to add to the Dll)
require("react");
require("react-bootstrap");
require("react-dom");
require("react-redux");
require("react-router-dom");
require("redux");
require("redux-form");
require("redux-promise");
require("redux-thunk");
require("classnames");
require("whatwg-fetch");
require("fetch");
require("prop-types");
require("url");
require("validator");
gulpfile.js
'use strict';
const gulp = require('gulp');
const webpack = require ('webpack');
const reactConfig = require('./webpack.config.js');
const vendorConfig = require('./webpack.dll.js');
// React webpack source build.
gulp.task('react-src', function (callback) {
webpack(reactConfig, function (err, stats) {
callback();
})
});
// React webpack vendor build.
gulp.task('react-vendor', function (callback) {
webpack(vendorConfig, function (err, stats) {
callback();
})
});
// Full webpack react build.
gulp.task('react-full', ['react-vendor', 'react-src']);
NOTE:
If I build my vendor-bundle with the terminal with webpack --config=webpack.dll.js first and it creates the vendor-manifest.json file, I can then subsequently successfully run my gulp tasks with no issues.
This is not very helpful though, as this still will not allow me to use webpack with gulp, as I intend to clean the build before new builds run.
I ended up using the solution mentioned in the end of my question. I build my DLL file first and then I can successfully run my gulp webpack tasks.
One change that can make it easier to debug the issue, is to use the Gulp utility module (gulp-util) to show any webpack errors that might show up during build of webpack, using gulp.
My final gulp setup ended up looking like this:
gulpfile.js
'use strict';
const gulp = require('gulp');
const gutil = require('gulp-util');
const webpack = require('webpack');
const reactConfig = require('./webpack.config.js');
const vendorConfig = require('./webpack.dll.js');
// React webpack source build.
gulp.task('react', function (callback) {
webpack(reactConfig, function (err, stats) {
if (err) {
throw new gutil.PluginError('webpack', err);
}
else {
gutil.log('[webpack]', stats.toString());
}
callback();
});
});
// React webpack vendor build.
gulp.task('react-vendor', function (callback) {
webpack(vendorConfig, function (err, stats) {
if (err) {
throw new gutil.PluginError('webpack', err);
}
else {
gutil.log('[webpack]', stats.toString());
}
callback();
});
});
// React: Rebuilds both source and vendor in the right order.
gulp.task('react-full', ['react-vendor'], function () {
gulp.start('react');
});
I hope this might help someone in a similar situation.
Whenever I run one of my defined gulp tasks, like gulp react-vendor I get an error, saying that it cannot resolve the vendor-manifest.json file.
Your gulpfile.js contains this:
const reactConfig = require('./webpack.config.js');
const vendorConfig = require('./webpack.dll.js');
And webpack.config.js contains this:
new webpack.DllReferencePlugin({
context: path.join(__dirname, "react", "src"),
manifest: require(path.join(__dirname, "react", "vendors", "vendor-manifest.json"))
}),
The require() calls are currently all executed immediately. Whenever you run Gulp, it will evaluate both Webpack configuration files. As currently configured, Node runs the code in webpack.config.js at startup, and from there it sees the require() used in your creation of the DllReferencePlugin, so it will also try to read manifest.json at that time and turn it into an object...which is before it has been built.
You can solve this in one of two ways:
The DllReferencePlugin's manifest option supports either an object (which is what you are currently providing), or else a string containing the path of the manifest file. In other words, it should work if you remove the require() from around your path.join(...) call.
Alternatively, you can also defer the loading of the Webpack config files. Moving your const reactConfig = require('./webpack.config.js'); from the top of the file directly into the gulp task function should be sufficient, assuming that this function is not invoked until after the manifest has been built.

Angular 1 + webpack produces huge file

I have been working on this angular webpack seed
Github link
After installing some modules, I saw that the app.bundle.js file becomes almost 15MB, and took too much time.
I have tried changing devtool to
config.devtool = 'cheap-module-source-map';
It reduces the file size to 200Kb almost, which is good, but then my application crashed with angular error
Error: [$injector:unpr] Unknown provider: t
'use strict';
// Modules
var path = require('path');
var webpack = require('webpack');
var autoprefixer = require('autoprefixer');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
/**
* Env
* Get npm lifecycle event to identify the environment
*/
var ENV = process.env.npm_lifecycle_event;
var isTest = ENV === 'test' || ENV === 'test-watch';
var isProd = ENV === 'build';
module.exports = function makeWebpackConfig() {
/**
* Config
* Reference: http://webpack.github.io/docs/configuration.html
* This is the object where all configuration gets set
*/
var config = {};
/**
* Entry
* Reference: http://webpack.github.io/docs/configuration.html#entry
* Should be an empty object if it's generating a test build
* Karma will set this when it's a test build
*/
config.entry = isTest ? void 0 : {
app: './app/app.js'
};
/**
* Output
* Reference: http://webpack.github.io/docs/configuration.html#output
* Should be an empty object if it's generating a test build
* Karma will handle setting it up for you when it's a test build
*/
config.output = isTest ? {} : {
// Absolute output directory
path: __dirname + '/dist',
// Output path from the view of the page
// Uses webpack-dev-server in development
publicPath: isProd ? '/' : 'http://localhost:8080/',
// Filename for entry points
// Only adds hash in build mode
filename: isProd ? '[name].[hash].js' : '[name].bundle.js',
// Filename for non-entry points
// Only adds hash in build mode
chunkFilename: isProd ? '[name].[hash].js' : '[name].bundle.js'
};
/**
* Devtool
* Reference: http://webpack.github.io/docs/configuration.html#devtool
* Type of sourcemap to use per build type
*/
if (isTest) {
config.devtool = 'inline-source-map';
}
else {
config.devtool = 'eval-source-map';
}
/**
* Loaders
* Reference: http://webpack.github.io/docs/configuration.html#module-loaders
* List: http://webpack.github.io/docs/list-of-loaders.html
* This handles most of the magic responsible for converting modules
*/
// Initialize module
config.module = {
rules: [{
// JS LOADER
// Reference: https://github.com/babel/babel-loader
// Transpile .js files using babel-loader
// Compiles ES6 and ES7 into ES5 code
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
}, {
// CSS LOADER
// Reference: https://github.com/webpack/css-loader
// Allow loading css through js
//
// Reference: https://github.com/postcss/postcss-loader
// Postprocess your css with PostCSS plugins
test: /\.css$/,
// Reference: https://github.com/webpack/extract-text-webpack-plugin
// Extract css files in production builds
//
// Reference: https://github.com/webpack/style-loader
// Use style-loader in development.
loader: isTest ? 'null-loader' : ExtractTextPlugin.extract({
fallbackLoader: 'style-loader',
loader: [
{loader: 'css-loader', query: {sourceMap: true}},
{loader: 'postcss-loader'}
],
})
}, {
// ASSET LOADER
// Reference: https://github.com/webpack/file-loader
// Copy png, jpg, jpeg, gif, svg, woff, woff2, ttf, eot files to output
// Rename the file using the asset hash
// Pass along the updated reference to your code
// You can add here any file extension you want to get copied to your output
test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/,
loader: 'file-loader'
}, {
// HTML LOADER
// Reference: https://github.com/webpack/raw-loader
// Allow loading html through js
test: /\.html$/,
loader: 'raw-loader'
}]
};
// ISTANBUL LOADER
// https://github.com/deepsweet/istanbul-instrumenter-loader
// Instrument JS files with istanbul-lib-instrument for subsequent code coverage reporting
// Skips node_modules and files that end with .test
if (isTest) {
config.module.rules.push({
enforce: 'pre',
test: /\.js$/,
exclude: [
/node_modules/,
/\.spec\.js$/
],
loader: 'istanbul-instrumenter-loader',
query: {
esModules: true
}
})
}
/**
* PostCSS
* Reference: https://github.com/postcss/autoprefixer-core
* Add vendor prefixes to your css
*/
// NOTE: This is now handled in the `postcss.config.js`
// webpack2 has some issues, making the config file necessary
/**
* Plugins
* Reference: http://webpack.github.io/docs/configuration.html#plugins
* List: http://webpack.github.io/docs/list-of-plugins.html
*/
config.plugins = [
new webpack.LoaderOptionsPlugin({
test: /\.scss$/i,
options: {
postcss: {
plugins: [autoprefixer]
}
}
}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
];
// Skip rendering index.html in test mode
if (!isTest) {
// Reference: https://github.com/ampedandwired/html-webpack-plugin
// Render index.html
config.plugins.push(
new HtmlWebpackPlugin({
template: './app/index.html',
inject: 'body'
}),
// Reference: https://github.com/webpack/extract-text-webpack-plugin
// Extract css files
// Disabled when in test mode or not in build mode
new ExtractTextPlugin({filename: 'css/[name].css', disable: !isProd, allChunks: true})
)
}
// Add build specific plugins
if (isProd) {
config.plugins.push(
// Reference: http://webpack.github.io/docs/list-of-plugins.html#noerrorsplugin
// Only emit files when there are no errors
new webpack.NoEmitOnErrorsPlugin(),
// Reference: http://webpack.github.io/docs/list-of-plugins.html#dedupeplugin
// Dedupe modules in the output
//new webpack.optimize.DedupePlugin(),
// Reference: http://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
// Minify all javascript, switch loaders to minimizing mode
new webpack.optimize.UglifyJsPlugin(),
// Copy assets from the public folder
// Reference: https://github.com/kevlened/copy-webpack-plugin
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, 'app/assets'),
to: path.resolve(__dirname, 'dist/assets')
}
])
)
}
/**
* Dev server configuration
* Reference: http://webpack.github.io/docs/configuration.html#devserver
* Reference: http://webpack.github.io/docs/webpack-dev-server.html
*/
config.devServer = {
contentBase: './dist',
stats: 'minimal'
};
return config;
}();

How to auto refresh browser with webpack on change?

I have a this file backend-dev.js which is mostly webpack configuration. I use it to run my express server from the bundled file. It stays on and restarts the server on any change. Is there any possible configuration can be added to auto refresh the browser too whenever I change the code?
This is what I have in the backend-dev.js:
const path = require('path');
const webpack = require('webpack');
const spawn = require('child_process').spawn;
const HtmlWebpackPlugin = require('html-webpack-plugin');
const compiler = webpack({
// add your webpack configuration here
entry: './app.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: "bundle.js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['env', 'es2015', 'stage-2']
}
}
}
]
},
/*plugins: [
new HtmlWebpackPlugin({
title: 'Project Demo',
hash: true,
template: './views/index.ejs' // Load a custom template (ejs by default see the FAQ for details)
})
],*/
node: {
__dirname: false
},
target: 'node'
});
const watchConfig = {
// compiler watch configuration
// see https://webpack.js.org/configuration/watch/
aggregateTimeout: 300,
poll: 1000
};
let serverControl;
compiler.watch(watchConfig, (err, stats) => {
if (err) {
console.error(err.stack || err);
if (err.details) {
console.error(err.details);
}
return;
}
const info = stats.toJson();
if (stats.hasErrors()) {
info.errors.forEach(message => console.log(message));
return;
}
if (stats.hasWarnings()) {
info.warnings.forEach(message => console.log(message));
}
if (serverControl) {
serverControl.kill();
}
// change filename to the relative path to the bundle created by webpack, if necessary(choose what to run)
serverControl = spawn('node', [path.resolve(__dirname, 'dist/bundle.js')]);
serverControl.stdout.on('data', data => console.log(data.toString()));
serverControl.stderr.on('data', data => console.error(data.toString()));
});
Excellent question: I solved it in the following way:
express has two modules you can install to refresh in hot without refreshing the browser, and it will refresh automatically: I leave you my configuration.
npm i livereload
npm i connect-livereload
const livereload = require('livereload');
const connectLivereload = require('connect-livereload');
const liveReloadServer = livereload.createServer();
liveReloadServer.watch(path.join(__dirname, '..', 'dist', 'frontend'));
const app = express();
app.use(connectLivereload());
Note that the folder you want to monitor is in dist/frontend. Change the folder you want to monitor so that it works: To monitor the backend I am using NODEMON
livereload open a port for the browser in the backend to expose the changes: how does the connection happen? It's easy; express with "connect-livereload" and inject a script that monitors that port: if a change occurs, the browser is notified by express, and the browser will refresh for you.
I leave The information as simple as possible to test, and I do not recommend using it like this: To use it you must separate the development and production environments. I keep it simple so that it is easy to understand.
Here I leave the most relevant link I found: I hope it will be helpful too.
https://bytearcher.com/articles/refresh-changes-browser-express-livereload-nodemon/

Webpack Never finishes

I'm working on a React project and I suddenly realize that when I starting my server, webpack never finishes(CPU usage is full and no output prints on the screen from webpack, I check it with -v switch and nothing changed.
How should id find the problem, Since I am unable to get any usable information from npm/webpack.
Edit:
when running with production Configuration it works fine, But in Development Configuration, it never stops. blow is my dev/prod configuration:
Dev:
/**
* DEVELOPMENT WEBPACK CONFIGURATION
*/
const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const logger = require('../../server/logger');
const cheerio = require('cheerio');
const pkg = require(path.resolve(process.cwd(), 'package.json'));
const dllPlugin = pkg.dllPlugin;
const plugins = [
new webpack.HotModuleReplacementPlugin(), // Tell webpack we want hot reloading
new webpack.NoErrorsPlugin(),
new HtmlWebpackPlugin({
inject: true, // Inject all files that are generated by webpack, e.g. bundle.js
templateContent: templateContent(), // eslint-disable-line no-use-before-define
}),
];
module.exports = require('./webpack.base.babel')({
// Add hot reloading in development
entry: [
'script!jquery/dist/jquery.js',
// 'script!materialize-css/dist/js/materialize.js',
'script!style/js/materialize.js',
'script!style/js/init.js',
'eventsource-polyfill', // Necessary for hot reloading with IE
'webpack-hot-middleware/client',
path.join(process.cwd(), 'app/app.js'), // Start with js/app.js
],
// Don't use hashes in dev mode for better performance
output: {
filename: '[name].js',
chunkFilename: '[name].chunk.js',
},
// Add development plugins
plugins: dependencyHandlers().concat(plugins).concat(new CircularDependencyPlugin({
// exclude detection of files based on a RegExp
exclude: /a\.js/,
// add errors to webpack instead of warnings
failOnError: true
})
), // eslint-disable-line no-use-before-define
// Load the CSS in a style tag in development
cssLoaders: 'style-loader!css-loader?localIdentName=[local]__[path][name]__[hash:base64:5]&importLoaders=1',
// Tell babel that we want to hot-reload
babelQuery: {
presets: ['react-hmre'],
},
// Emit a source map for easier debugging
// devtool: 'cheap-module-eval-source-map',
devtool: 'source-map',
});
/**
* Select which plugins to use to optimize the bundle's handling of
* third party dependencies.
*
* If there is a dllPlugin key on the project's package.json, the
* Webpack DLL Plugin will be used. Otherwise the CommonsChunkPlugin
* will be used.
*
*/
function dependencyHandlers() {
// Don't do anything during the DLL Build step
if (process.env.BUILDING_DLL) {
return [];
}
// If the package.json does not have a dllPlugin property, use the CommonsChunkPlugin
if (!dllPlugin) {
return [
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
children: true,
minChunks: 2,
async: true,
}),
];
}
const dllPath = path.resolve(process.cwd(), dllPlugin.path || 'node_modules/react-boilerplate-dlls');
/**
* If DLLs aren't explicitly defined, we assume all production dependencies listed in package.json
* Reminder: You need to exclude any server side dependencies by listing them in dllConfig.exclude
*
* #see https://github.com/mxstbr/react-boilerplate/tree/master/docs/general/webpack.md
*/
if (!dllPlugin.dlls) {
const manifestPath = path.resolve(dllPath, 'reactBoilerplateDeps.json');
if (!fs.existsSync(manifestPath)) {
logger.error('The DLL manifest is missing. Please run `npm run build:dll`');
process.exit(0);
}
return [
new webpack.DllReferencePlugin({
context: process.cwd(),
manifest: require(manifestPath), // eslint-disable-line global-require
}),
];
}
// If DLLs are explicitly defined, we automatically create a DLLReferencePlugin for each of them.
const dllManifests = Object.keys(dllPlugin.dlls).map((name) => path.join(dllPath, `/${name}.json`));
return dllManifests.map((manifestPath) => {
if (!fs.existsSync(path)) {
if (!fs.existsSync(manifestPath)) {
logger.error(`The following Webpack DLL manifest is missing: ${path.basename(manifestPath)}`);
logger.error(`Expected to find it in ${dllPath}`);
logger.error('Please run: npm run build:dll');
process.exit(0);
}
}
return new webpack.DllReferencePlugin({
context: process.cwd(),
manifest: require(manifestPath), // eslint-disable-line global-require
});
});
}
/**
* We dynamically generate the HTML content in development so that the different
* DLL Javascript files are loaded in script tags and available to our application.
*/
function templateContent() {
const html = fs.readFileSync(
path.resolve(process.cwd(), 'app/index.html')
).toString();
if (!dllPlugin) {
return html;
}
const doc = cheerio(html);
const body = doc.find('body');
const dllNames = !dllPlugin.dlls ? ['reactBoilerplateDeps'] : Object.keys(dllPlugin.dlls);
dllNames.forEach((dllName) => body.append(`<script data-dll='true' src='/${dllName}.dll.js'></script>`));
return doc.toString();
}
Prod:
// Important modules this config uses
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const OfflinePlugin = require('offline-plugin');
module.exports = require('./webpack.base.babel')({
// In production, we skip all hot-reloading stuff
entry: [
'script!jquery/dist/jquery.min.js',
// 'script!materialize-css/dist/js/materialize.min.js',
'script!style/js/materialize.min.js',
'script!style/js/init.js',
path.join(process.cwd(), 'app/app.js'),
],
// Utilize long-term caching by adding content hashes (not compilation hashes) to compiled assets
output: {
filename: '[name].[chunkhash].js',
chunkFilename: '[name].[chunkhash].chunk.js',
},
// We use ExtractTextPlugin so we get a separate CSS file instead
// of the CSS being in the JS and injected as a style tag
cssLoaders: ExtractTextPlugin.extract({
fallbackLoader: 'style-loader',
loader: 'css-loader?modules&-autoprefixer&importLoaders=1!postcss-loader',
}),
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
children: true,
minChunks: 2,
async: true,
}),
// OccurrenceOrderPlugin is needed for long-term caching to work properly.
// See http://mxs.is/googmv
new webpack.optimize.OccurrenceOrderPlugin(true),
// Merge all duplicate modules
new webpack.optimize.DedupePlugin(),
// Minify and optimize the JavaScript
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false, // ...but do not show warnings in the console (there is a lot of them)
},
}),
// Minify and optimize the index.html
new HtmlWebpackPlugin({
template: 'app/index.html',
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
inject: true,
}),
// Extract the CSS into a separate file
new ExtractTextPlugin('[name].[contenthash].css'),
// Put it in the end to capture all the HtmlWebpackPlugin's
// assets manipulations and do leak its manipulations to HtmlWebpackPlugin
new OfflinePlugin({
relativePaths: false,
publicPath: '/',
// No need to cache .htaccess. See http://mxs.is/googmp,
// this is applied before any match in `caches` section
excludes: ['.htaccess'],
caches: {
main: [':rest:'],
// All chunks marked as `additional`, loaded after main section
// and do not prevent SW to install. Change to `optional` if
// do not want them to be preloaded at all (cached only when first loaded)
additional: ['*.chunk.js'],
},
// Removes warning for about `additional` section usage
safeToUseOptionalCaches: true,
AppCache: false,
}),
],
});

Categories

Resources