Integrating with webpack-isomorphic-tools - javascript

I'm trying to develop a react isomorphic app, and i've recently came up with the webpack-isomorphic-tools npm package.
I've tried to follow the documentation but unfortunately the images and style files doesn't get recognized, and not added to the webpack-assets.json file.
Up until now I've used this method:
if(process.env.BROWSER){
include('./style.scss');
}
But I understood webpack-isomorphic-tools is more beneficial.
for scss and other style files this is the error i get when running the server:
[webpack-isomorphic-tools] [debug] requiring ./shared/Root.scss
[webpack-isomorphic-tools] [error] asset not found: ./shared/Root.scss
for image files no errors are shown during the build, since no images are detected on the build. here is the webpack-assets.js:
{
"javascript": {
"main": "/build/bundle.js"
},
"styles": {},
"assets": {}
}
Relevant code:
webpack-isomorphic-tools-config.js:
var webpack_isomorphic_tools_plugin = require('webpack-isomorphic-tools/plugin');
module.exports =
{
debug: true,
webpack_assets_file_path : 'public/build/webpack-assets.json',
webpack_stats_file_path : 'public/build/webpack-stats.json',
assets:
{
images:
{
extensions: ['png', 'jpg', 'gif', 'ico', 'svg']
},
fonts:
{
extensions: ['woff', 'woff2', 'eot', 'ttf']
},
styles:
{
extensions: ['scss', 'less', 'css'],
filter(module, regular_expression, options, log)
{
if (options.development)
{
// In development mode there's Webpack "style-loader",
// which outputs `module`s with `module.name == asset_path`,
// but those `module`s do not contain CSS text.
//
// The `module`s containing CSS text are
// the ones loaded with Webpack "css-loader".
// (which have kinda weird `module.name`)
//
// Therefore using a non-default `filter` function here.
//
return webpack_isomorphic_tools_plugin.style_loader_filter(module, regular_expression, options, log)
}
// In production mode there will be no CSS text at all
// because all styles will be extracted by Webpack Extract Text Plugin
// into a .css file (as per Webpack configuration).
//
// Therefore in production mode `filter` function always returns non-`true`.
},
// How to correctly transform kinda weird `module.name`
// of the `module` created by Webpack "css-loader"
// into the correct asset path:
path: webpack_isomorphic_tools_plugin.style_loader_path_extractor,
// How to extract these Webpack `module`s' javascript `source` code.
// Basically takes `module.source` and modifies its `module.exports` a little.
parser: webpack_isomorphic_tools_plugin.css_loader_parser
}
}
}
index.js (looks a lot like the one in the documentation):
'use strict';
var path = require('path');
require('babel-register');
require('babel-polyfill');
require('app-module-path').addPath(path.join(__dirname,'shared'));
global._development_ = false
if (process.env.NODE_ENV !== 'production'){
global._development_ = true;
}
var Webpack_isomorphic_tools = require('webpack-isomorphic-tools');
// this must be equal to your Webpack configuration "context" parameter
var project_base_path = path.resolve(__dirname);
// this global variable will be used later in express middleware
global.webpack_isomorphic_tools = new Webpack_isomorphic_tools(require('./webpack-isomorphic-tools-config'))
// enter development mode if needed
// (you may also prefer to use a Webpack DefinePlugin variable)
.development(!(process.env.NODE_ENV === 'production'))
// initializes a server-side instance of webpack-isomorphic-tools
// (the first parameter is the base path for your project
// and is equal to the "context" parameter of you Webpack configuration)
// (if you prefer Promises over callbacks
// you can omit the callback parameter
// and then it will return a Promise instead)
.server(project_base_path, function()
{
// webpack-isomorphic-tools is all set now.
// here goes all your web application code:
// (it must reside in a separate *.js file
// in order for the whole thing to work)
require('./server/server')
});
webpack.dev.js (webpack-dev-server config):
var path = require('path');
var webpack = require('webpack');
var Webpack_isomorphic_tools_plugin = require('webpack-isomorphic-tools/plugin')
var webpack_isomorphic_tools_plugin =
// webpack-isomorphic-tools settings reside in a separate .js file
// (because they will be used in the web server code too).
new Webpack_isomorphic_tools_plugin(require('./webpack-isomorphic-tools-config'))
// also enter development mode since it's a development webpack configuration
// (see below for explanation)
.development();
module.exports = {
context: __dirname,
entry: ['webpack-dev-server/client?http://127.0.0.1:8080/',
'webpack/hot/only-dev-server',
'./client/index.jsx'],
resolve: {
modulesDirectories: ['node_modules', 'shared'],
extensions: ['', '.js', '.jsx']
},
output: {
path: path.join(__dirname, 'public', 'build'),
filename: 'bundle.js',
publicPath: "/build/"
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['react-hot', 'babel']
},
{
test: /\.css$/,
loader: "style-loader!css-loader!autoprefixer-loader"
},
{
test: /\.less$/,
loader: "style-loader!css-loader!autoprefixer-loader!less-loader"
},
{
test: /\.scss$/,
loader: "style-loader!css-loader!autoprefixer-loader!sass-loader"
},
{
test: webpack_isomorphic_tools_plugin.regular_expressions['images'],
loader: "url-loader?limit=10240"
},
{
test: webpack_isomorphic_tools_plugin.regular_expression['fonts'],
loader: "url-loader?limit=10240"
}
]
},
plugins: [
new webpack.DefinePlugin({
"process.env": {
BROWSER: JSON.stringify(true),
NODE_ENV: JSON.stringify( process.env.NODE_ENV || 'development' )
}
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
webpack_isomorphic_tools_plugin
],
devtool: 'inline-source-map',
devServer: {
hot: true,
proxy: {
'*': 'http://127.0.0.1:' + (process.env.PORT || 3000)
},
host: '127.0.0.1'
}
};
webpack.config.js:
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var Webpack_isomorphic_tools_plugin = require('webpack-isomorphic-tools/plugin')
var webpack_isomorphic_tools_plugin =
// webpack-isomorphic-tools settings reside in a separate .js file
// (because they will be used in the web server code too).
new Webpack_isomorphic_tools_plugin(require('./webpack-isomorphic-tools-config'));
module.exports = {
context: __dirname,
entry: ['./client/index.jsx'],
resolve: {
modulesDirectories: ['node_modules', 'shared'],
extensions: ['', '.js', '.jsx']
},
output: {
path: path.join(__dirname, 'public', 'build'),
filename: 'bundle.js',
publicPath: "/build"
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['react-hot', 'babel']
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader!autoprefixer-loader")
},
{
test: /\.less$/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader!autoprefixer-loader!less-loader")
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader!autoprefixer-loader!sass-loader")
},
{
test: /\.gif$/, loader: "url-loader?limit=10000&mimetype=image/gif"
},
{
test: /\.jpg$/, loader: "url-loader?limit=10000&mimetype=image/jpg"
},
{
test: /\.png$/, loader: "url-loader?limit=10000&mimetype=image/png"
},
{
test: /\.svg/, loader: "url-loader?limit=26000&mimetype=image/svg+xml"
},
{
test: /\.(woff|woff2|ttf|eot)/, loader: "url-loader?limit=1&name=/[hash].[ext]"
}
]
},
plugins: [
new webpack.DefinePlugin({
"process.env": {
BROWSER: JSON.stringify(true),
NODE_ENV: JSON.stringify( process.env.NODE_ENV || 'development' )
}
}),
new ExtractTextPlugin("bundle.css")
]
};
If more code is required, I'd be happy to give it, thanks!

Related

Source mapping with webpack for express server

I have an express server that is written in es5 and es6 combined. It consists of js and ts files. So now when I make a webpack build and start the server, it runs fine. But if my code throws an error then the error tracing is not correct i.e source of error (file, line and column number) is not showing correctly.
Is there a way to map the bundle with the source?
I have tried adding:
devTool: "source-map" to webpack config but it doesn't work, it seems to be working with the browser. Is there any way to achieve the same for server-side as well?
Here is my webpack.config.js
const nodeExternals = require("webpack-node-externals");
const webpack = require("webpack");
const path = require("path");
module.exports = {
stats: "detailed",
target: "node",
externals: [nodeExternals()],
entry: {
app: "./server.js",
backupCronApp: "./backup/cron/index.js"
},
output: {
path: path.join(__dirname, "/build"),
filename: "[name].js",
libraryTarget: "commonjs2",
},
plugins: [new webpack.EnvironmentPlugin(["NODE_ENV"])],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: "babel-loader",
},
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.ts', '.js'],
},
};

WebPack output.library.type var is undefined

I am learning WebPack with a shortcode. In the code, we are trying to calculate the cube and square. They will suppose to store in a variable as per the following webpack.config.js.
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const isDevelopment = process.env.NODE_ENV === 'development';
const config = {
entry: './src/index.ts',
output: {
path: path.resolve(__dirname, 'dist'),
library: {
type: 'var',
name: 'testVar'
},
filename: '[name].js'
},
mode: 'production',
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: "[name].css",
chunkFilename: "[id].css",
}),
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 1,
}),
new HtmlWebpackPlugin({
hash: true,
title: 'Video Player Play Ground',
myPageHeader: 'Sample Video Player',
template: './src/index.html',
filename: 'index.html'
})
],
module: {
rules: [
{
test: /\.s[ac]ss$/i,
exclude: /node_modules/,
use: [
// fallback to style-loader in development
MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader",
],
},
{
test: /\.ts(x)?$/,
loader: 'ts-loader',
exclude: /node_modules/
},
{
test: /\.svg$/,
use: 'file-loader'
}
]
},
resolve: {
extensions: [
'.tsx',
'.ts',
'.js',
'.scss'
]
},
optimization: {
usedExports: true,
runtimeChunk: false,
minimize: false
}
};
module.exports = config;
As shown in the above config, we store the compiled javascript in the variable with the name "testVar".
The above approach working fine when we are using the following command line code "webpack --mode production"
In the final generated javascript file we have a line which equals to
testVar = webpack_exports;
Also, testVar.start is working fine.
But the above approach is not working when we are using the following command line "webpack serve --mode production" or "webpack serve"
When we run a local server, the testVar.start is undefined. I am not sure what I am doing wrong.
Following is the code we are using in the index.html file to call the start function, which we defined in our internal javascript
window.onload = function (){
alert(testVar);
console.log(testVar);
if(testVar.start !== undefined)
{
alert(testVar.start);
console.log(testVar.start);
testVar.start(3,2);
}
else {
alert("Start Function is undefined");
}
}
Also following is the code insight from index.ts and math.ts.
import {cube, square} from './math';
export function start(c:number, s:number) {
console.log(cube(c));
console.log(square(s));
}
export function square(x:number) {
return x * x;
}
export function cube(x:number) {
return x * x * x;
}
enter image description here
Finally, I got it working :-).
I need to add the following line in my webpack.config.js
devServer: {
injectClient: false
},
Following is the reference URL: https://github.com/webpack/webpack-dev-server/issues/2484
Don't forget to Vote it. Thanks.

How do I fingerprint images and other static assets in Ionic for cache busting?

I have extended default web pack config in Ionic v3 for forcing cache busting.
I am able to fingerprint generated JavaScript artifacts, but I am unable to fingerprint images and JSON files under the assets folder. I took Help from Bundled files and cache-busting.
An excerpt of webpack config.js
module.exports = {
// ...
output: {
filename: '[name].[chunkhash].js',
chunkFilename: '[name].[chunkhash].js',
},
plugins: [
new WebpackChunkHash({algorithm: 'md5'}) // 'md5' is default value
]
}
The above is the approach for fingerprinting JavaScript bundles, and it's working fine. I want to add hashes/fingerprint images and JSON files inside the assets folder. I used the same approach for images also, but it did not work.
I have extended webpack config.js and added a new rule for images. By default webpack directly copies the images and assets to the output folder.
Copy Config.js
module.exports = {
copyAssets: {
src: ['{{SRC}}/assets/**/*'],
dest: '{{WWW}}/assets'
},
copyIndexContent: {
src: ['{{SRC}}/index.html', '{{SRC}}/manifest.json', '{{SRC}}/service-worker.js'],
dest: '{{WWW}}'
},
copyFonts: {
src: ['{{ROOT}}/node_modules/ionicons/dist/fonts/**/*', '{{ROOT}}/node_modules/ionic-angular/fonts/**/*'],
dest: '{{WWW}}/assets/fonts'
},
Here images and other assets are directly copied.
I have added a new rule in extended webpack.config.js, but the build process is ignoring it. How do I fix this issue?
Excerpt of webpack config.js
{
test: /\.(png|jpg|gif)$/,
loader: 'file-loader',
options: {
name:'[name].[hash].[ext]',//adding hash for cache busting
outputPath:'assets/imgs',
publicPath:'assets/imgs'
},
entire Webpack.config.js
/*
* The webpack config exports an object that has a valid webpack configuration
* For each environment name. By default, there are two Ionic environments:
* "dev" and "prod". As such, the webpack.config.js exports a dictionary object
* with "keys" for "dev" and "prod", where the value is a valid webpack configuration
* For details on configuring webpack, see their documentation here
* https://webpack.js.org/configuration/
*/
var path = require('path');
var webpack = require('webpack');
var ionicWebpackFactory = require(process.env.IONIC_WEBPACK_FACTORY);
var ModuleConcatPlugin = require('webpack/lib/optimize/ModuleConcatenationPlugin');
var PurifyPlugin = require('#angular-devkit/build-optimizer').PurifyPlugin;
var optimizedProdLoaders = [
{
test: /\.json$/,
loader: 'json-loader'
},
{
test: /\.js$/,
loader: [
{
loader: process.env.IONIC_CACHE_LOADER
},
{
loader: '#angular-devkit/build-optimizer/webpack-loader',
options: {
sourceMap: true
}
},
]
},
{
test: /\.ts$/,
loader: [
{
loader: process.env.IONIC_CACHE_LOADER
},
{
loader: '#angular-devkit/build-optimizer/webpack-loader',
options: {
sourceMap: true
}
},
{
test: /\.(png|jpg|gif)$/,
loader: 'file-loader',
options: {
name:'[name].[hash].[ext]',
outputPath:'assets/imgs',
publicPath:'assets/imgs'
},
},
{
loader: process.env.IONIC_WEBPACK_LOADER
}
]
}
];
function getProdLoaders() {
if (process.env.IONIC_OPTIMIZE_JS === 'true') {
return optimizedProdLoaders;
}
return devConfig.module.loaders;
}
var devConfig = {
entry: process.env.IONIC_APP_ENTRY_POINT,
output: {
path: '{{BUILD}}',
publicPath: 'build/',
filename: '[name].js',
devtoolModuleFilenameTemplate: ionicWebpackFactory.getSourceMapperFunction(),
},
devtool: process.env.IONIC_SOURCE_MAP_TYPE,
resolve: {
extensions: ['.ts', '.js', '.json'],
modules: [path.resolve('node_modules')]
},
module: {
loaders: [
{
test: /\.json$/,
loader: 'json-loader'
},
{
test: /\.ts$/,
loader: process.env.IONIC_WEBPACK_LOADER
},
{
test: /\.(jpg|png)$/,
use: {
loader: "file-loader",
options: {
name: "[name].[hash].[ext]",
outputPath:'assets/imgs',
publicPath:'assets/imgs'
},
}},
]
},
plugins: [
ionicWebpackFactory.getIonicEnvironmentPlugin(),
ionicWebpackFactory.getCommonChunksPlugin()
],
// Some libraries import Node.js modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
fs: 'empty',
net: 'empty',
tls: 'empty'
}
};
var prodConfig = {
entry: process.env.IONIC_APP_ENTRY_POINT,
output: {
path: '{{BUILD}}',
publicPath: 'build/',
filename: '[name].js',
devtoolModuleFilenameTemplate: ionicWebpackFactory.getSourceMapperFunction(),
},
devtool: process.env.IONIC_SOURCE_MAP_TYPE,
resolve: {
extensions: ['.ts', '.js', '.json'],
modules: [path.resolve('node_modules')]
},
module: {
loaders: getProdLoaders()
},
plugins: [
ionicWebpackFactory.getIonicEnvironmentPlugin(),
ionicWebpackFactory.getCommonChunksPlugin(),
new ModuleConcatPlugin(),
new PurifyPlugin()
],
// Some libraries import Node.js modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
fs: 'empty',
net: 'empty',
tls: 'empty'
}
};
module.exports = {
dev: devConfig,
prod: prodConfig
}
Using Webpack 4 you should not need any additional plugins or loaders.
It will give you the naming option [contenthash].
Also, it looks like you have this block nested under the test: .ts block.
{
test: /\.(png|jpg|gif)$/,
loader: 'file-loader',
options: {
name:'[name].[hash].[ext]', // Adding hash for cache busting
outputPath:'assets/imgs',
publicPath:'assets/imgs'
}
}
Ultimately, you can do something like this:
// Copy static assets over with file-loader
{
test: /\.(ico)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader', options: {name: '[name].[contenthash].[ext]'},
},
{
test: /\.(woff|woff2|eot|ttf|otf)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader', options: {name: 'fonts/[name].[contenthash].[ext]'},
},
{
test: /\.(jpg|gif|png|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'file-loader', options: {name: 'images/[name].[contenthash].[ext]'},
}
]
Using [chunkhash] instead of content should still work, and if you're not using webpack4 do that, but otherwise for more information see this issue for an explanation.
For more help, read the long-term caching performance guide from Google and the latest caching documentation from Webpack.
the files copied via CopyPlugin will not pass to loaders.
So even you have correct loader setting with hashname for images, it doesn't work.
but you can see https://github.com/webpack-contrib/copy-webpack-plugin#template
the CopyPlugin provide you a way to specify output name which can be set with hash:
module.exports = {
plugins: [
new CopyPlugin([
{
from: 'src/',
to: 'dest/[name].[hash].[ext]',
toType: 'template',
},
]),
],
};
Eventually, I used gulp for fingerprinting static assets.
Drop Angular Output hashing and build the application.ng build --prod --aot --output-hashing none .
post-build execute a gulp script which would fingerprint all the assets and update the references.
npm i gulp gulp-rev gulp-rev-delete-original gulp-rev-collector
gulpfile.js
const gulp = require('gulp');
const rev = require('gulp-rev');
const revdel = require('gulp-rev-delete-original');
const collect = require('gulp-rev-collector');
// finger priniting static assets
gulp.task('revision:fingerprint', () => {
return gulp
.src([
'dist/welcome/**/*.css',
'dist/welcome/**/*.js',
'dist/welcome/**/*.{jpg,png,jpeg,gif,svg,json,xml,ico,eot,ttf,woff,woff2}'
])
.pipe(rev())
.pipe(revdel())
.pipe(gulp.dest('dist/welcome'))
.pipe(rev.manifest({ path: 'manifest-hash.json' }))
.pipe(gulp.dest('dist'));
});
gulp.task('revision:update-fingerprinted-references', () => {
return gulp
.src(['dist/manifest-hash.json', 'dist/**/*.{html,json,css,js}'])
.pipe(collect())
.pipe(gulp.dest('dist'));
});
gulp.task(
'revision',
gulp.series(
'revision:fingerprint',
'revision:update-fingerprinted-references'));
Add a new script in package.json
"gulp-revision": "gulp revision"
Execute npm run gulp-revision Post-build.
Solving Browser Cache Hell With Gulp-Rev
Using webpack-assets-manifest you can generate a map of asset names to fingerprinted names like so:
{
"images/logo.svg": "images/logo-b111da4f34cefce092b965ebc1078ee3.svg"
}
Using this manifest you can then rename the assets in destination folder, and use the "correct", hash-inclusive src or href in your project.
The fix isn't framework-specific.

angular2 bundle node_modules only and not application code

Angular v.4 and webpack
i am looking for answer of very simple question.
How can i bundle node_module folder as vendor.js but not your application code. on page load seems like there are more then 300 requests from angular code to load internal files.
if i am able to merge all node_modules libraries i will save lot of browser requests.
I followed this example was able to get it run but it bundles libraries and your application code as well. i was able to successfully generate the vendor.js only but i am not sure after i add vendor.js in index.html how my application code will recognize #angular lib references. currently it is being resolved using systemjs.config.js some thing like this
#angular/code : 'npm:#angular/code/bundle/core.umd.js'
..
..
and exactly thats what happen as i thought application crashed it can't find references to #angular from my application code.
is it possible to just bundle node_module folder into vendor.js and still able to use in my application code without bundling app code ?
adding webpack config
webpack.config.js
module.exports = require('./config/webpack.prod.js');
webpack.common.js
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var helpers = require('./helpers');
module.exports = {
entry: {
'polyfills': './src/polyfills.ts',
'vendor': './src/vendor.ts',
'app': './src/main.ts'
},
resolve: {
extensions: ['.ts', '.js']
},
module: {
rules: [
{
test: /\.ts$/,
loaders: [
{
loader: 'awesome-typescript-loader',
options: { configFileName: helpers.root('src', 'tsconfig.json') }
} , 'angular2-template-loader'
]
},
{
test: /\.html$/,
loader: 'html-loader'
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: 'file-loader?name=assets/[name].[hash].[ext]'
},
{
test: /\.css$/,
exclude: helpers.root('src', 'app'),
loader: ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: 'css-loader?sourceMap' })
},
{
test: /\.css$/,
include: helpers.root('src', 'app'),
loader: 'raw-loader'
}
]
},
plugins: [
// Workaround for angular/angular#11580
new webpack.ContextReplacementPlugin(
// The (\\|\/) piece accounts for path separators in *nix and Windows
/angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
helpers.root('./src'), // location of your src
{} // a map of your routes
),
new webpack.optimize.CommonsChunkPlugin({
name: ['app', 'vendor', 'polyfills']
}),
new HtmlWebpackPlugin({
template: 'src/index.html'
})
]
};
webpack.prod.js
var webpack = require('webpack');
var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var helpers = require('./helpers');
const ENV = process.env.NODE_ENV = process.env.ENV = 'production';
module.exports = webpackMerge(commonConfig, {
devtool: 'source-map',
output: {
path: helpers.root('dist'),
publicPath: '/',
filename: '[name].[hash].js',
chunkFilename: '[id].[hash].chunk.js'
},
plugins: [
new webpack.NoEmitOnErrorsPlugin(),
new webpack.optimize.UglifyJsPlugin({ // https://github.com/angular/angular/issues/10618
mangle: {
keep_fnames: true
}
}),
new ExtractTextPlugin('[name].[hash].css'),
new webpack.DefinePlugin({
'process.env': {
'ENV': JSON.stringify(ENV)
}
}),
new webpack.LoaderOptionsPlugin({
htmlLoader: {
minimize: false // workaround for ng2
}
})
]
});

Prevent display of raw HTML in react

Is there a way to prevent in React.js, raw HTML display before the CSS stylesheets are completely loaded. I'm using Webpack, Semantic-UI (react version) and React.js.
Is there an equivalent of ng-cloak (angular) in React ?
Here's the content of my webpack config file :
const webpack = require('webpack')
const ManifestPlugin = require('webpack-manifest-plugin')
const path = require("path");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const DEBUG = process.env.NODE_ENV !== 'production'
const plugins = [
new webpack.DefinePlugin({
'process.env.NODE_ENV': `"${process.env.NODE_ENV}"`
})
]
const assetsDir = process.env.ASSETS_DIR
const assetMapFile = process.env.ASSETS_MAP_FILE
const outputFile = DEBUG ? '[name].js' : '[name].[chunkhash].js'
if (!DEBUG) {
plugins.push(new ManifestPlugin({
fileName: assetMapFile
}))
plugins.push(new webpack.optimize.UglifyJsPlugin({ minimize: true }))
}
const config = {
entry: {
bundle: ['babel-polyfill', './src/client/index.jsx']
},
module: {
noParse: [],
loaders: [
{ test: /\.json$/, loader: 'json' },
{ test: /\.css$/, loader: 'style!css' },
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /(node_modules|bower_components)/,
query: {
cacheDirectory: DEBUG
}
},
{test:/.svg$/,loader:'url-loader',query:{mimetype:'image/svg+xml',
name:'/semantic/themes/default/assets/fonts/icons.svg'}},
{test:/.woff$/,loader:'url-loader',query:{mimetype:'application/font-woff',
name:'/semantic/themes/default/assets/fonts/icons.woff'}},
{test:/.woff2$/,loader:'url-loader',query:{mimetype:'application/font-woff2',
name:'/semantic/themes/default/assets/fonts/icons.woff2'}},
{test:/.[ot]tf$/,loader:'url-loader',query:{mimetype:'application/octet-stream',
name:'/semantic/themes/default/assets/fonts/icons.ttf'}},
{test:/.eot$/,loader:'url-loader',query:{mimetype:'application/vnd.ms-fontobject',
name:'/semantic/themes/default/assets/fonts/icons.eot'}},
{ test: /\.png/, loader: "url-loader?limit=100000&minetype=image/png" },
{ test: /\.jpg/, loader: "file-loader" }
]
},
node: {
fs: "empty"
},
resolve: {
alias: {
"semantic-ui" : path.resolve( __dirname, "../semantic/dist/semantic.min.css")
},
extensions: ['', '.js', '.jsx', ".css"]
},
plugins,
output: {
filename: outputFile,
path: DEBUG ? '/' : assetsDir,
publicPath: '/assets/'
}
}
if (DEBUG) {
config.devtool = '#inline-source-map'
} else if (process.env.NODE_ENV === 'production') {
config.devtool = 'source-map'
}
module.exports = config
I got this error when I try to load my css from my component :
Cannot find module '/semantic/dist/semantic.min.css'
and the module exists.
I tried the exact same configuration without Webpack and import from component worked.
This is not the correct setup for a production deploy.
By default, Webpack turns your CSS into Javascript code that injects CSS tags in the page. This allows for hot CSS reloading. It's only appropriate for the development environment, obviously. You should be using this default behavior in dev, and should not be using it in production.
In production, you need to build a separate CSS file and load it normally with a <style> tag in your production HTML code. To tell Webpack to pull that out into a file, use the ExtractTextPlugin, which your code requires but never uses.
You should maintain two Webpack config files, one for development which doesn't extract text (and doesn't minify/uglify, etc), and one for production, which correctly minifies, hashes names, extracts text, etc.

Categories

Resources