Why does Webpack think I’m running a development build? - javascript

This is an older project that will soon get some updates, but until then I need to use the original Webpack configs. The strange thing is this hasn’t been touched since the last release, yet there is a blocking issue.
When bundling for production and running in the browser, I get the following message:
Uncaught Error: Minified exception occurred; use the non-minified dev
environment for the full error message and additional helpful
warnings.
It seems like Webpack thinks I’m running in development mode but using the minified React files, hence the message. I’ve traced all occurrences of process.env.NODE_ENV and they all log "production".
This is the build command that bundles the files:
node --max_old_space_size=3072 node_modules/.bin/webpack --verbose --colors --display-error-details --config webpack/prod.config.js
… and the Webpack configuration:
require('babel/polyfill');
// Webpack config for creating the production bundle.
const path = require('path');
const webpack = require('webpack');
const strip = require('strip-loader');
const projectRootPath = path.resolve(__dirname, '../');
const assetsPath = path.resolve(projectRootPath, './static/dist');
const webpackPostcssTools = require('webpack-postcss-tools');
const map = webpackPostcssTools.makeVarMap('./src/theme/index.css');
// https://github.com/halt-hammerzeit/webpack-isomorphic-tools
const WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin');
const webpackIsomorphicToolsPlugin = new WebpackIsomorphicToolsPlugin(require('./webpack-isomorphic-tools'));
module.exports = {
devtool: 'source-map',
context: path.resolve(__dirname, '..'),
entry: {
'main': [
'./src/client.js'
]
},
output: {
path: assetsPath,
filename: '[name]-[chunkhash].js',
chunkFilename: '[name]-[chunkhash].js',
publicPath: '/dist/'
},
module: {
loaders: [
{ test: /\.jsx?$/, exclude: /node_modules/, loaders: [strip.loader('debug'), 'babel']},
{ test: /\.json$/, loader: 'json-loader' },
{ test: /\.css$/, loaders: ['style', 'css?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss'] },
{ test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=10&mimetype=application/font-woff' },
{ test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: 'url-loader?limit=10&mimetype=application/font-woff' },
{ test: /\.svg$/, loader: 'svg-inline' },
{ test: webpackIsomorphicToolsPlugin.regular_expression('images'), loader: 'url-loader?limit=10' },
{ test: /\.modernizrrc$/, loader: 'modernizr' }
]
},
progress: true,
resolve: {
alias: {
font: __dirname + '/../src/fonts',
images: __dirname + '/../static/images',
modernizr$: path.resolve(__dirname, '../.modernizrrc')
},
modulesDirectories: [
'src',
'node_modules'
],
extensions: ['', '.json', '.js', '.jsx']
},
postcss: () => {
return [
require('autoprefixer')({
browsers: ['last 3 versions']
}),
require('precss'),
require('postcss-custom-media')({
extensions: map.media
})
];
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
'Scribe': 'scribe-editor'
}),
new webpack.DefinePlugin({
__CLIENT__: true,
__SERVER__: false,
__DEVELOPMENT__: false,
__DEVTOOLS__: false
}),
// ignore dev config
new webpack.IgnorePlugin(/\.\/dev/, /\/config$/),
// set global vars
new webpack.DefinePlugin({
'process.env': {
// Useful to reduce the size of client-side libraries, e.g. react
NODE_ENV: JSON.stringify('production'),
API_HOST: JSON.stringify(process.env.API_HOST || 'api'),
WEB_HOST: JSON.stringify(process.env.WEB_HOST || 'https://www.website.com')
}
}),
// optimizations
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
webpackIsomorphicToolsPlugin
]
};
I cannot seem to find the problem. Anything jump out that looks fishy?

Because your code is set to production, it's getting minified and you're getting that message.
Try setting it to development (i.e. NODE_ENV: JSON.stringify('development'))
React - Minified exception occurred

Related

Using Imports with .Net, React.Js, and Url.Content

I am using a .Net MVC framework, and trying to render a jsx (React) file that has imports. I am including this file in the razor page (cshtml) through the standard Url.Content injection as follows:
<script src="#Url.Content("~/js/queue/QueueIndex.js")"></script>
<script>
ReactDOM.render(React.createElement(QueueIndex), document.getElementById("queue-index"));
jQuery(window).on("load scroll", function () {
'use strict'; // Start of use strict
// Loader
$("#dvLoading").fadeOut("fast");
});
</script>
If I do not have an import at the top of my React file (QueueIndex.jsx) the page loads just fine. However, I would like to import the react-table package, but if include any imports in my QueueIndex.jsx file, the page breaks.
The error I'm getting is require is not defined.
I think the solution is somewhere in the use of webpack, here is my config:
const webpack = require("webpack");
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: {
nhqueue: './wwwroot/js/queue/QueueIndex.jsx'
},
output: {
path: __dirname + '/wwwroot/js/',
publicPath: '/wwwroot/js/',
filename: '[name].bundle.js'
},
module: {
preLoaders: [
],
loaders: [
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{ test: /\.tsx?$/, loaders: ['babel', 'ts'] },
{ test: /\.json$ /, loader: "json-loader" },
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: "babel",
query:
{
presets: ['react']
}
}
],
externals: {
"moment": "moment",
},
},
devtool: 'source-map',
target: 'web',
plugins: [
new CleanWebpackPlugin(['./wwwroot/js/*.js'], {
root: __dirname,
verbose: true,
dry: false
}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
}),
new webpack.optimize.UglifyJsPlugin()
],
resolve: {
extensions: ['', '.jsx', '.js', '.tsx', '.ts']
},
node: {
fs: "empty",
child_process: "empty"
}
}
Unfortunately, I have had no luck there. Please let me know if you have any ideas of how to resolve this issue. Thanks!
Also, Here is the Babel configuration:
{"presets" : ["es2015", "react"]}

Uncaught ReferenceError: require is not defined - Webpack2

I'm updating an app to use webpack 2 from webpack 1 and the regular build works fine. The issue seems to arise when using the devServer and requiring just one of the chunks generated (it's an electron app so I have main and renderer chunks - both are included in a regular build, and with the dev server only the renderer chunk is included)
Everything worked on webpack 1, but for some reason the runtime isn't being included in my chunks? I've tried reordering them but to no avail.
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const path = require('path');
module.exports = {
context: __dirname,
entry: {
main: './main.js',
renderer: './app/index.jsx'
},
output: {
path: path.resolve(__dirname, './dist'),
filename: "[name].js"
},
node: {
__dirname: false,
__filename: false
},
devtool: 'cheap-eval-source-map',
target: 'electron',
module: {
loaders: [
{
test: /(\.js$|\.jsx$)/,
exclude: /(node_modules|dist)/,
loader: 'babel'
},
{ test: /\.scss$/, loader: "style!css?modules!sass" },
{ test: /\.png$/, loader: "url?limit=100000" },
{ test: /\.jpg$/, loader: "file" }
]
},
resolve: {
extensions: ['.js', '.jsx', '.scss'],
modules: [path.resolve('./app'), 'node_modules']
},
plugins: [
new HtmlWebpackPlugin({
template: './app/index.html',
chunks: ['renderer'],
inject: 'body',
hash: 'true'
}),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': '"dev"'
}
})
],
devServer: {
contentBase: __dirname
},
externals: {
'cheerio': 'window',
'react/addons': true,
'react/lib/ExecutionEnvironment': true,
'react/lib/ReactContext': true
}
};
It seems one of the chunks isn't included properly:
/***/ },
/* 26 */
/***/ function(module, exports) {
module.exports = require("url");
Why is this?
So it seems the issue was with me setting the target to electron but building for web. This seemed to work in webpack 1, but after updating to webpack 2 it no longer includes the runtime in both bundles.
The solution I took was to have two configs - one for electron (my main build), and one for web (specify the target in the webpack config)

How can I load a url (path) of a picture or others in a file of your build (prod) with webpack

I have some questions about webpack and the interaction with the path of libraries.
This is my webpack-config.js:
var path = require('path'),
webpack = require("webpack"),
libPath = path.join(__dirname, 'lib'),
distPath = path.join(__dirname, 'dist'),
HtmlWebpackPlugin = require('html-webpack-plugin'),
os = require('os'),
ImageminPlugin = require('imagemin-webpack-plugin').default,
OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin'),
CopyWebpackPlugin = require('copy-webpack-plugin'),
webpackUglifyJsPlugin = require('webpack-uglify-js-plugin'),
ProgressBarPlugin = require('progress-bar-webpack-plugin'); // To be deleted when webpack will accept the flag --progress in the devserver and not only in the command line
var cf = {
entry: path.join(libPath, 'index.js'),
output: {
path: path.join(distPath),
filename: 'bundle-[hash:6].js'
},
resolveLoader: { root: path.join(__dirname, 'node_modules') },
module: {
loaders: [
{
test: /\.html$/,
loader: 'file?name=lib/templates/[name]-[hash].html'
},
{
test: /\.scss$/,
loaders: ['style', 'css', 'sass', 'resolve-url', 'sass?sourceMap']
},
{
test: /\.css$/,
loaders: ["style-loader", "css-loader"]
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url-loader?limit=10000&mimetype=application/font-woff&&name=lib/font/[name]-[hash].[ext]'
},
{
test: /\.jpe?g$|\.gif$|\.png$/,
loaders: ['file?hash=sha512&digest=hex&name=lib/img/[name]-[hash].[ext]',
'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'] // I write for the moment lib/img because i have not the choice but i don't want write in the same folder that the dev env
},
{
test: /\.ttf$|\.eot$|\.wav$|\.svg$/,
loader: "file?name=lib/font/[name]-[hash].[ext]"
},
{
test: /\.json$/,
loaders: ["raw-loader", "file?name=lib/languages/[name]-[hash].[ext]"]
},
{
test: /\.js$/,
exclude: /(node_modules)/,
loaders: ['ng-annotate?add=true', 'babel']
}
]
},
devServer: {
port: 3001,
compress:true,
colors:true
},
plugins: [
// HtmlWebpackPlugin: Simplifies creation of HTML files to serve your webpack bundles : https://www.npmjs.com/package/html-webpack-plugin
new HtmlWebpackPlugin({
inject: true,
filename: 'index.html',
title: 'MY_CUSTOM_APP',
template: path.join(libPath, 'index.html')
}),
// Deduplication: find duplicate dependencies & prevents duplicate inclusion : https://github.com/webpack/docs/wiki/optimization#deduplication
new webpack.optimize.DedupePlugin(),
// OccurenceOrderPlugin: Assign the module and chunk ids by occurrence count. : https://webpack.github.io/docs/list-of-plugins.html#occurenceorderplugin
new webpack.optimize.OccurenceOrderPlugin(),
new OptimizeCssAssetsPlugin({
cssProcessor: require('cssnano'),
cssProcessorOptions: { discardComments: {removeAll: true } },
canPrint: true
}),
new ImageminPlugin({
disable: false,
optipng: {
optimizationLevel: 3
},
gifsicle: {
optimizationLevel: 1
},
jpegtran: {
progressive: false
},
svgo: {
},
pngquant: null, // pngquant is not run unless you pass options here
plugins: []
}),
// a faire uniquement en prod
new webpackUglifyJsPlugin ({
cacheFolder: path.resolve(__dirname, 'dist/cached_uglify/'),
sourceMap: false,
minimize: false,
compressor: {
warnings: false
}
}),
new ProgressBarPlugin({format: ' build [:bar] ' + (':percent') + ' (:elapsed seconds)'})
]
};
module.exports = cf;
This is my call of angular directive:
<complete-block
header-img="./lib/img/image.jpg"
body-title="{{ 'BODY_TITLE' | translate }}"
body-text="{{ 'LOREM_1' | translate }}"></complete-block>
My problem is about the url for the picture.
In my dist build ( production), I have only a root folder dist and then under it, I have the img folder.
In more, the picture has a hash so finally I have something like that: dist/img/mypicture-56567465456354354.png instead of lib/img/mypicture.png.
How can I load it with the hash in the directive and also if it's not the same path between the dev env and the prod env ?
Sorry if it's trivial, all of this is new for me and I didn't find a solution about it :/
Thank you ! :)
Edit 1 (07/01/2017) : My work is opensource, so you can find it on github here: https://github.com/kevincaradant/web-template-webpack
The picture / link is here :
.../lib/components/home/home.component.js
.../lib/components/home/home.html
You need to require the image in the js file. It will give you the path of the image to use in the code. eg :
var image = require('./lib/img/image.jpg'); // returns 'dist/img/mypicture-56567465456354354.png'
<complete-block
header-img="{{ image }}"
body-title="{{ 'BODY_TITLE' | translate }}"
body-text="{{ 'LOREM_1' | translate }}"></complete-block>

Webpack does not compress the files enough

this is my webpack config that I use for development and production modes;
let debug = process.env.NODE_ENV !== 'production';
import webpack from "webpack";
import LiveReloadPlugin from "webpack-livereload-plugin";
import WebpackNotifierPlugin from "webpack-notifier";
import validate from "webpack-validator";
import failPlugin from "webpack-fail-plugin";
import autoprefixer from "autoprefixer";
let loaders = [
{test: /\.tsx?$/, loader: 'ts', exclude: /(node_modules)/},
{
test : /\.js?$/,
exclude: /(node_modules)/,
loader : 'babel', // 'babel-loader' is also a legal name to reference
query : {
presets : ['es2015'],
cacheDirectory: true
}
},
{
test : /\.(eot|ttf|wav|mp3|png|jpg|jpeg|gif|svg|woff|woff2)$/,
loader: 'url-loader',
},
{
test : /\.scss$/,
loaders: [
"style-loader",
"css-loader",
"postcss-loader",
"sass-loader?outputStyle=compressed"
]
}
];
let globaljQuery = {
$ : 'jquery',
jQuery : 'jquery',
'window.jQuery': 'jquery'
};
let devPlugins = [
new WebpackNotifierPlugin({excludeWarnings: true}),
new webpack.ProvidePlugin(globaljQuery),
new LiveReloadPlugin(),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
// new ExtractTextPlugin('css/app.css', {allChunks: true}),
failPlugin,
];
let prodPlugins = [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress : {warnings: false},
output : {comments: false},
sourceMap: false
}),
new webpack.ProvidePlugin(globaljQuery)
];
module.exports = validate({
context: __dirname,
devtool: 'eval',
resolve: {
extensions: ['', '.webpack.js', '.web.js', '.ts', '.js'],
alias : {jquery: __dirname + '/resources/assets/js/libs/jquery-3.1.0.min.js'}
},
entry : [
// 'webpack/hot/dev-server',
// 'webpack-dev-server/client?http://localhost:8081',
__dirname + '/resources/assets/js/main.js'
],
output : {
path : __dirname + '/public',
publicPath: '/public/',
filename : 'js/app.js'
},
plugins: debug ? devPlugins : prodPlugins,
module : {
loaders: loaders,
},
postcss: () => {
return [autoprefixer]
}
});
But for some reason if I minify modules individually it compiles to a smaller bundle than if I delegate the same task to webpack in production mode.
For example if I use uncompressed "owl carousel" plugin and delegate compressing task to webpack the bundle is 43 kb larger.
Plugins such as photoswipe make the bundle around 82kb larger.
jQuery is about 120kb larger...
What do I miss that compressing individual plugins manually is more efficient, as from my point of view the webpack should be doing this task automatically and compressing files to same level as doing it manually...?

Preferred way of using Bootstrap in Webpack

Greetings one and all,
I have been playing around with Bootstrap for Webpack, but I'm at the point of tearing my hair out. I have literally gone through loads of blog articles and they either use the 7 months outdated 'bootstrap-webpack' plugin (which, surprisingly does not work out of the box) or.. They include the Bootstrap files through import 'node_modules/*/bootstrap/css/bootstrap.css'.
Surely, there must be a cleaner and more efficient way of going about this?
This is my current webpack.config.js file:
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var autoprefixer = require('autoprefixer');
var path = require('path');
module.exports = {
entry: {
app: path.resolve(__dirname, 'src/js/main.js')
},
module: {
loaders: [{
test: /\.js[x]?$/,
loaders: ['babel-loader?presets[]=es2015&presets[]=react'],
exclude: /(node_modules|bower_components)/
}, {
test: /\.css$/,
loaders: ['style', 'css']
}, {
test: /\.scss$/,
loaders: ['style', 'css', 'postcss', 'sass']
}, {
test: /\.sass$/,
loader: 'style!css!sass?sourceMap'
},{
test: /\.less$/,
loaders: ['style', 'css', 'less']
}, {
test: /\.woff$/,
loader: "url-loader?limit=10000&mimetype=application/font-woff&name=[path][name].[ext]"
}, {
test: /\.woff2$/,
loader: "url-loader?limit=10000&mimetype=application/font-woff2&name=[path][name].[ext]"
}, {
test: /\.(eot|ttf|svg|gif|png)$/,
loader: "file-loader"
}]
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '/js/bundle.js',
sourceMapFilename: '/js/bundle.map',
publicPath: '/'
},
plugins: [
new ExtractTextPlugin('style.css')
],
postcss: [
autoprefixer({
browsers: ['last 2 versions']
})
],
resolve: {
extensions: ['', '.js', '.sass'],
modulesDirectories: ['src', 'node_modules']
},
devServer: {
inline: true,
contentBase: './dist'
}
};
I could go and require('bootstrap') (with some way of getting jQuery in it to work), but.. I'm curious to what you all think and do.
Thanks in advance :)
I am not sure if this is the best way, but following work for me well with vue.js webapp. You can see the working code here.
I have included files required by bootstrap in index.html like this:
<head>
<meta charset="utf-8">
<title>Hey</title>
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
<link rel="stylesheet" href="/static/bootstrap.css" type="text/css">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.3.7/js/tether.min.js" integrity="sha384-XTs3FgkjiBgo8qjEjBk0tGmf3wPrWtA6coPfQDfFEY8AnYJwjalXCiosYRBIBZX8" crossorigin="anonymous"></script>
<script href="/static/bootstrap.js"></script>
</head>
And this works, you can execute the repo. Why I went this way was I had to customise some config in bootstrap so I had to change the variables file and build the code of bootstrap which outputted me bootstrap.js and bootstrap.cssfiles, which I am using here.
There is an alternative way suggested here by using the npm package and a webpack customisation.
First install bootstrap in your project:
npm install bootstrap#4.0.0-alpha.5
And make sure you can use sass-loader in your components:
npm install sass-loader node-sass --save-dev
now go to your webpack config file and add a sassLoader object with the following:
sassLoader: {
includePaths: [
path.resolve(projectRoot, 'node_modules/bootstrap/scss/'),
],
},
projectRoot should just point to where you can navigate to node_packages from, in my case this is: path.resolve(__dirname, '../')
Now you can use bootstrap directly in your .vue files and webpack will compile it for you when you add the following:
<style lang="scss">
#import "bootstrap";
</style>
I highly recommend using bootstrap-loader. You add a config file (.bootstraprc in your root folder) where you can exclude the bootstrap elements you don't want and tell where your variables.scss and bootstrap.overrides.scss are. Define you SCSS variables, do your overrides, add your webpack entry and get on with your life.
I use webpack to build bootstrap directly from .less and .scss files. This allows customizing bootstrap by overriding the source in .less/.scss and still get all the benefits of webpack.
Your code is missing an entry point for any .css/.less/.scss files. You need to include an entry point for the compiled css files. For this entry point, I declare an array with const and then include paths inside the array to the source files I want webpack to compile.
Currently, I'm using bootstrap 3 with a base custom template and also a 2nd custom theme. The base template uses bootstrap .less file styling and it has specific source overrides written in .less files.
The 2nd custom theme uses .sass file styling and has similar overrides to bootstrap's base written in .scss files. So, I need to try to optimize all this styling for production (currently coming in about 400kb but that's a little heavy because we choose to avoid CDN's due to targeting use in China).
Below is a reference webpack.config.js which works to build from .less/.scss/.css files, and also does a few other things like build typescript modules and uses Babel for converting es6/typescript to browser compatible javascript. The output ultimately ends up in my /static/dist folder.
const path = require('path');
const webpack = require('webpack');
// plugins
const ForkTsCheckerNotifierWebpackPlugin = require('fork-ts-checker-notifier-webpack-plugin');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const MomentLocalesPlugin = require('moment-locales-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserJSPlugin = require('terser-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
// take debug mode from the environment
const debug = (process.env.NODE_ENV !== 'production');
// Development asset host (webpack dev server)
const publicHost = debug ? 'http://localhost:9001' : '';
const rootAssetPath = path.join(__dirname, 'src');
const manifestOptions = {
publicPath: `${publicHost}/static/dist/`,
};
const babelLoader = {
loader: 'babel-loader',
options: {
cacheDirectory: true,
presets: [
'#babel/preset-env'
]
}
};
const app_css = [
// specific order generally matters
path.join(__dirname, 'src', 'bootstrap-template1', 'assets', 'css', 'fonts', 'Roboto', 'css', 'fonts.css'),
path.join(__dirname, 'node_modules', 'font-awesome', 'css', 'font-awesome.css'),
// This is bootstrap 3.3.7 base styling writtin in .less
path.join(__dirname, 'src', 'bootstrap-template1', 'assets', 'less', '_main_full', 'bootstrap.less'),
// bootstrap theme in .scss -> src\bp\folder\theme\src\scss\styles.scss
path.join(__dirname, 'src', 'bp', 'folder', 'theme', 'src', 'scss', 'styles.scss'),
// back to .less -> 'src/bootstrap-template1/assets/less/_main_full/core.less',
path.join(__dirname, 'src', 'bootstrap-template1', 'assets', 'less', '_main_full', 'core.less'),
// 'src/bootstrap-template1/assets/less/_main_full/components.less',
path.join(__dirname, 'src', 'bootstrap-template1', 'assets', 'less', '_main_full', 'components.less'),
//'src/bootstrap-template1/assets/less/_main_full/colors.less',
path.join(__dirname, 'src', 'bootstrap-template1', 'assets', 'less', '_main_full', 'colors.less'),
// <!-- syntax highlighting in .css --> src/bp/folder/static/css/pygments.css
path.join(__dirname, 'src', 'bp', 'folder', 'static', 'css', 'pygments.css'),
// <!-- lato/ptsans font we want to serve locally --> src/fonts/googlefonts.css'
path.join(__dirname, 'src', 'fonts', 'googlefonts.css'),
// a .css style -> 'src/bp/appbase/styles/md_table_generator.css'
path.join(__dirname, 'src', 'bp', 'appbase', 'styles', 'md_table_generator.css'),
// another .css style -> hopscotch 'src/libs/hopscotch/dist/css/hopscotch.min.css'
path.join(__dirname, 'src', 'libs', 'hopscotch', 'dist', 'css', 'hopscotch.min.css'),
//LAST final custom snippet styles to ensure they take priority 'src/css/style.css',
path.join(__dirname, 'src', 'css', 'style.css')
];
const vendor_js = [
//'core-js',
'whatwg-fetch',
];
const app_js = [
// a typescript file! :)
path.join(__dirname, 'src', 'typescript', 'libs', 'md-table', 'src', 'extension.ts'),
// base bootstrap 3.3.7 javascript
path.join(__dirname, 'node_modules', 'bootstrap', 'dist', 'js', 'bootstrap.js'),
path.join(__dirname, 'src', 'main', 'app.js'),
// src/bootstrap-template1/assets/js/plugins/forms/styling/uniform.min.js'
path.join(__dirname, 'node_modules', '#imanov', 'jquery.uniform', 'src', 'js', 'jquery.uniform.js'),
// src/bootstrap-template1/assets/js/plugins/ui/moment/moment.min.js'
];
function recursiveIssuer(m) {
if (m.issuer) {
return recursiveIssuer(m.issuer);
} else if (m.name) {
return m.name;
} else {
return false;
}
}
module.exports = {
context: process.cwd(), // to automatically find tsconfig.json
// context: __dirname,
entry: {
app_css,
vendor_js,
app_js,
},
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: `${publicHost}/static/dist/`,
chunkFilename: '[id].[hash:7].js',
filename: '[name].[hash:7].js'
},
resolve: {
extensions: [".webpack.js", ".web.js",".tsx", ".ts", ".js", ".css"],
alias: {
jquery$: path.resolve(__dirname, 'node_modules', 'jquery', 'dist', 'jquery.js'),
}
},
target: "web",
devtool: 'source-map',
devServer: {
// this devserver proxies all requests to my python development server except
// webpack compiled files in the `/static/dist` folder
clientLogLevel: 'warning',
contentBase: path.join(__dirname, './src'),
publicPath: 'dist',
open: true,
historyApiFallback: true,
stats: 'errors-only',
headers: {'Access-Control-Allow-Origin': '*'},
watchContentBase: true,
port: 9001,
proxy: {
'!(/dist/**/**.*)': {
target: 'http://127.0.0.1:8000',
},
},
},
mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
optimization: {
minimizer: [new TerserJSPlugin({}), new OptimizeCssAssetsPlugin({})],
splitChunks: {
cacheGroups: {
appStyles: {
name: 'app',
// https://webpack.js.org/plugins/mini-css-extract-plugin/#extracting-css-based-on-entry
test: (m, c, entry = 'app') =>
m.constructor.name === 'CssModule' && recursiveIssuer(m) === entry,
chunks: 'all',
enforce: true,
},
},
},
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
'window.$': 'jquery'
}),
// Strip all locales from moment.js except "zh-cn"
// ("en" is built into Moment and can’t be removed)
new MomentLocalesPlugin({
localesToKeep: ['zh-cn'],
}),
new ForkTsCheckerWebpackPlugin({
tslint: true, useTypescriptIncrementalApi: true
}),
new ForkTsCheckerNotifierWebpackPlugin({ title: 'TypeScript', excludeWarnings: false }),
new MiniCssExtractPlugin({
filename: '[name].[hash:7].css',
chunkFilename: '[id].[hash:7].css',
moduleFilename: ({ name }) => `${name.replace('/js/', '/css/')}.[hash:7].css`
}),
new OptimizeCssAssetsPlugin({
assetNameRegExp: /\.optimize\.css$/g,
cssProcessor: require('cssnano'),
cssProcessorPluginOptions: {
preset: ['default', { discardComments: { removeAll: true } }],
},
canPrint: true
}),
new ManifestPlugin({
...manifestOptions
}),
].concat(debug ? [] : [
// production webpack plugins go here
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
}
}),
new ForkTsCheckerWebpackPlugin({
async: false,
useTypescriptIncrementalApi: true,
memoryLimit: 2048
}),
]),
module: {
rules: [
{
// jinja/nunjucks templates
test: /\.jinja2$/,
loader: 'jinja-loader',
query: {
root:'../templates'
}
},
{
test: /\.ts(x?)$/,
exclude: /node_modules/,
use: [
babelLoader,
{
loader: 'ts-loader',
options:
{ // disable type checker - we will use it in
// fork-ts-checker-webpack-plugin
transpileOnly: true
}
}
]
},
{
test: /\.js$/,
exclude: /node_modules/,
use: [
babelLoader
]
},
{
test: /\.(html|jinja2)$/,
loader: 'raw-loader'
},
{
test: /\.(sc|sa|c)ss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: debug,
// only use if hmr is not working correctly
// reloadAll: true,
},
},
{
loader: "css-loader",
},
{
loader: "sass-loader"
},
]
},
{
test: /\.less$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: debug,
// only use if hmr is not working correctly
// reloadAll: true,
},
},
{
loader: 'css-loader', // translates CSS into CommonJS
},
{
loader: 'less-loader', // compiles Less to CSS
},
],
},
{
test: /\.(ttf|eot|svg|gif|ico)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[path][name].[hash:7].[ext]',
context: rootAssetPath
},
},
],
},
{
test: /\.(jpe?g|png)$/i,
loader: 'responsive-loader',
options: {
name: '[path][name].[hash:7].[ext]',
adapter: require('responsive-loader/sharp'),
context: rootAssetPath
}
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader:'url-loader',
options:{
limit: 10000,
mimetype: 'application/font-woff',
// name: ('fonts/[path][name].[hash:7].[ext]'),
name: ('fonts/[name].[hash:7].[ext]'),
}
},
{
test: require.resolve("jquery"),
use:[
{ loader: "expose-loader", options:"$" },
{ loader: "expose-loader", options:"jQuery" },
{ loader: "expose-loader", options:"jquery" }
]
}
]
},
};

Categories

Resources