Webpack 4 – simple js function not working after bundled files - javascript

I’m relatively new to webpack. I’m trying to make a simple architecture work, but can’t seem to find out what’s wrong. I’m going to try to summarize my code:
package.json file:
"devDependencies": {
"#babel/preset-env": "^7.8.3",
"babel-loader": "^8.0.6",
"babel-preset-es2015": "^6.24.1",
"bootstrap": "^4.4.1",
"clean-webpack-plugin": "^3.0.0",
"css-loader": "^3.4.2",
"file-loader": "^5.0.2",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"jest": "^24.9.0",
"jest-cli": "^24.9.0",
"jquery": "^3.4.1",
"mini-css-extract-plugin": "^0.9.0",
"node-sass": "^4.13.1",
"optimize-css-assets-webpack-plugin": "^5.0.3",
"popper.js": "^1.16.1",
"sass-loader": "^8.0.2",
"style-loader": "^1.1.3",
"webpack": "^4.41.5",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.10.1",
"webpack-merge": "^4.2.2"
}
webpack.config.js file:
"use strict";
const path = require("path");
const merge = require("webpack-merge");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const TerserPlugin = require("terser-webpack-plugin");
module.exports = {
mode: "production",
devtool: "none",
entry: {
"backend":"./src/backend.src.js"
},
output: {
filename: "[name].bundle.js",
path: path.resolve(__dirname, "dist")
},
optimization: {
minimize: true,
concatenateModules: true,
namedModules: true,
minimizer: [
new TerserPlugin(),
new OptimizeCssAssetsPlugin()
]
},
plugins: [
new HtmlWebpackPlugin({
minify: {
collapseWhitespace: true,
removeComments: true
}
}),
new MiniCssExtractPlugin({filename: "styles-[name].bundle.css"}),
new CleanWebpackPlugin()
],
module: {
rules: [
//CSS.
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader"
]
},
//SASS.
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader"
]
}
//JS (transpile to es5)
{
test: /\.js$/,
use: [
{
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"]
}
}
]
},
//HTML
{
test: /\.html$/,
use: [
"html-loader"
]
},
//Files
{
test: /\.(svg|png|jpg|jpeg|gif)$/,
use: {
loader: "file-loader",
options: {
name: "[name].[hash].[ext]",
outputPath: "imgs",
esModule: false
}
}
}
]
}
};
backend.src.js file:
"use strict";
import '../app_styles/styles-backend.css';
import { webpackDebugTest } from '../app_js/functions-syncsystem.js';
functions-syncsystem.js file:
"use strict";
export function webpackDebugTest()
{
alert("Webpack test - inside function");
}
index.html file (simple, plain html where i´m importing the the bundled files in order to test):
(simple html)
<script>
webpackDebugTest();
</script>
(simple html)
When I run the index, the css file loads fine, the js file also loads fine, but it doesn´t seem to recognize the simple js function I created in order to test the architecture. Console gives me an error message like this:
Uncaught ReferenceError: webpackDebugTest is not defined
I’ve also tried changing the functions-syncsystem.js file to the following:
"use strict";
function webpackDebugTest()
{
alert("Webpack test - inside function");
}
module.exports = {
webpackDebugTest: webpackDebugTest
};
And in the bundled file, I can find the following code:
e.exports={webpackDebugTest:function(){alert("Webpack test - inside function")}
And it still returns me that same error message on the console panel.
Anyone can detect what could be the issue with my usage?

entry: {
backend:"./src/backend.src.js"
},
in order to use "import" you need to install this
npm i #babel/register --save
on top of your entry point files
require("#babel/register")

Related

Error: Cannot read property 'eval' of null when compiling less in webpack using webpack-spritesmith

The error is coming from the LESS file that webpack-spritesmith plugin is generating:
ERROR in ./assets/less/main.less
Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js):
ModuleBuildError: Module build failed (from ./node_modules/less-loader/dist/cjs.js):
#spritesheet-sprites:;
#spritesheet: 0px 0px '~img/generated/sprite.png' #spritesheet-sprites;
Cannot read property 'eval' of null
For some reason, the spritesheet-sprites variable seems to be defined without a value. I encountered this error after I upgraded my Webpack version from 1.13 to 5.22 (along with its loaders). I tried downgrading some of the dependencies like less, less-loader, and the webpack-spritesmith plugin itself, but didn't seem to work. Also checked if the newer versions of Webpack and its loaders handle paths differently, no result.
I wrote the configs (for webpack and the plugins) by following their official documents, everything seems to be in place but by checking resources online I couldn't find whether my configuration is wrong or that there are unmatching versions in the packages.
My webpack config:
const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const SpritesmithPlugin = require('webpack-spritesmith');
const mainPath = path.join(__dirname, './assets');
module.exports = {
mode: 'production',
stats: 'verbose',
resolve: {
extensions: ['.js'],
alias: {
assets: mainPath,
js: path.join(mainPath, 'js'),
less: path.join(mainPath, 'less'),
img: path.join(mainPath, 'img'),
fonts: path.join(mainPath, 'fonts')
},
},
entry: ['./assets/index'],
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].js',
publicPath: './',
chunkFilename: '[id].[chunkhash].js'
},
module: {
rules: [
{
test: /\.js?/,
exclude: /(node_modules)/,
include: path.join(__dirname, 'assets'),
use: ['babel-loader']
},
{
test: /\.(ttf|eot|svg|woff|woff2)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: ['file-loader']
},
{
test: /\.jpe?g$|\.gif$|\.png$/i,
use: ['file-loader']
},
{
test: /\.less$/,
use: [MiniCssExtractPlugin.loader, 'style-loader', 'css-loader', 'less-loader'],
},
],
},
plugins: [
new SpritesmithPlugin({
src: {
cwd: path.resolve(__dirname, 'assets/img/sprite'),
glob: '*.png'
},
target: {
image: path.resolve(__dirname, 'assets/img/generated/sprite.png'),
css: path.resolve(__dirname, 'assets/less/generated/sprite.less')
},
apiOptions: {
cssImageRef: "~img/generated/sprite.png",
generateSpriteName: function(filePath) {
return 'sprite-' + path.basename(filePath, '.png');
}
}
}),
new MiniCssExtractPlugin({filename: 'style.css'})
]
};
package.json:
"devDependencies": {
"#babel/core": "^7.12.16",
"#babel/preset-env": "^7.12.16",
"babel-eslint": "7.0.0",
"babel-loader": "^8.2.2",
"cross-env": "3.0.0",
"css-loader": "^5.0.2",
"eslint": "3.7.0",
"eslint-plugin-babel": "3.3.0",
"eslint-plugin-react": "6.3.0",
"file-loader": "^6.2.0",
"less": "^3.0.0",
"less-loader": "^8.0.0",
"mini-css-extract-plugin": "^1.3.7",
"rimraf": "2.5.4",
"style-loader": "^2.0.0",
"unused-files-webpack-plugin": "^3.4.0",
"webpack": "^5.22.0",
"webpack-cli": "^4.5.0",
"webpack-dev-middleware": "1.8.3",
"webpack-hot-middleware": "2.12.2",
"webpack-spritesmith": "^1.1.0"
}

How to bundle Nunjucks files via Webpack

I have a complete site that I want to design a build tool for it.In fact, I chose Webpack for doing that. The project structure is like this:
I have nunjucks, html, css, sass and js files. I must bundle them via webpack. My webpack config file is here:
var HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const path = require('path')
const CopyPlugin = require('copy-webpack-plugin')
const NunjucksWebpackPlugin = require('nunjucks-webpack-plugin')
module.exports = {
entry: ['./src/index.js'],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
devtool: 'inline-source-map',
devServer: {
contentBase: './dist',
writeToDisk: true
},
plugins: [
new CopyPlugin([
{ from: 'public/images', to: 'images' },
{ from: 'public/fonts', to: 'fonts' },
{ from: 'src/pages/about', to: '.' }
]),
new CleanWebpackPlugin(),
// new HtmlWebpackPlugin()
new HtmlWebpackPlugin({
title: 'Asset Management' //title of file.html
})
],
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
'style-loader',
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader'
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ['file-loader']
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: ['file-loader']
},
{
test: /\.(njk|nunjucks)$/,
loader: 'nunjucks-loader'
},
{
// to auto refresh index.html and other html
test: /\.html$/,
loader: 'raw-loader',
exclude: /node_modules/
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
options: {
interpolate: true
}
}
]
}
]
}
}
The "index.js" file also is like this:
import _ from 'lodash'
import './pages/about/about_moon.scss'
import './pages/about/about_moon.html'
var tpl = require('./pages/home/index_moon.njk')
var html = tpl.render({ message: 'Foo that!' })
function component() {
return element
}
document.body.appendChild(component())
I configured the "package.json" file and defined scripts to run webpack:
"start": "webpack-dev-server --open",
"build": "webpack"
The problem is when I run npm run build, the dist folder was made and it had a html file but there is nothing to show. I have already had some html files and wanted to bundle all of them to "bundle.js", but I have not known how. Would you please tell me how I can bundle this project?
Thank you in advance.
Problem solved. I changed the Webpack.config.js file to this:
const path = require('path')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var UglifyJSPlugin = require('uglifyjs-webpack-plugin')
const CopyPlugin = require('copy-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const BrowserSyncPlugin = require('browser-sync-webpack-plugin')
module.exports = {
entry: ['./src/index.js', './script.js'],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
// HtmlWebpackPluginConfig
new HtmlWebpackPlugin({
filename: 'index.html',
inject: 'head',
template: './index.njk'
}),
new CleanWebpackPlugin(),
new CopyPlugin([
{ from: 'public/images', to: 'images' },
{ from: 'public/fonts', to: 'fonts' }
])
],
module: {
rules: [
{
test: /\.exec\.js$/,
use: ['script-loader']
},
{
test: /\.css$/i,
use: ['style-loader', 'css-loader']
},
{
test: /\.(scss)$/,
use: [
{
// Adds CSS to the DOM by injecting a `<style>` tag
loader: 'style-loader'
},
{
// Interprets `#import` and `url()` like `import/require()` and will resolve them
loader: 'css-loader'
},
{
// Loader for webpack to process CSS with PostCSS
loader: 'postcss-loader',
options: {
plugins: function() {
return [require('autoprefixer')]
}
}
},
{
// Loads a SASS/SCSS file and compiles it to CSS
loader: 'sass-loader'
}
]
},
{
// HTML LOADER
// Super important: We need to test for the html
// as well as the nunjucks files
test: /\.html$|njk|nunjucks/,
use: [
'html-loader',
{
loader: 'nunjucks-html-loader',
options: {
// Other super important. This will be the base
// directory in which webpack is going to find
// the layout and any other file index.njk is calling.
// searchPaths: [...returnEntries('./src/pages/**/')]
// Use the one below if you want to use a single path.
// searchPaths: ['./']
}
}
]
}
]
}
}
Also, I wrote the script.js file like this, since, function names were changed and they could not be run after bundling.
document.getElementById('body').onload = function() {
console.log('Document loaded')
var menu = localStorage.getItem('menu')
if (menu === 'opened')
document.getElementById('navigation').classList.add('opened')
}
document.getElementById('menu-button').onclick = function() {
// localstorage used to define global variable
var menu = localStorage.getItem('menu')
localStorage.setItem('menu', menu === 'closed' ? 'opened' : 'closed')
document.getElementById('navigation').classList.toggle('opened')
}
// Window.onLoad = onLoad // global variable in js
The index.js was used to import other files and it was like this:
import _ from 'lodash'
require('../index.njk')
require('../base.html')
require('../style.css')
This is the Json file:
{
"name": "menu_moon",
"version": "1.0.0",
"description": "",
"private": true,
"dependencies": {
"browser-sync": "^2.26.7",
"extract-text-webpack-plugin": "^3.0.2",
"fast-glob": "^3.1.1",
"fs-extra": "^8.1.0",
"g": "^2.0.1",
"html-loader": "^0.5.5",
"i": "^0.3.6",
"lodash": "^4.17.15",
"mkdirp": "^0.5.1",
"nunjucks": "^3.2.0",
"nunjucks-html-loader": "^1.1.0",
"nunjucks-isomorphic-loader": "^2.0.2",
"nunjucks-loader": "^3.0.0",
"raw-loader": "^4.0.0"
},
"devDependencies": {
"browser-sync-webpack-plugin": "^2.2.2",
"clean-webpack-plugin": "^3.0.0",
"copy-webpack-plugin": "^5.0.5",
"css-loader": "^3.2.1",
"file-loader": "^5.0.2",
"html-webpack-plugin": "^3.2.0",
"node-sass": "^4.13.0",
"nunjucks-webpack-plugin": "^5.0.0",
"sass-loader": "^8.0.0",
"script-loader": "^0.7.2",
"style-loader": "^1.0.1",
"uglifyjs-webpack-plugin": "^2.2.0",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.9.0"
},
"scripts": {
"moon-start": "browser-sync start --server --files './**/*.*'",
"moon-build": "node build_product_moon.js",
"start": "webpack-dev-server --open",
"build": "webpack"
},
"author": "",
"license": "ISC"
}
I hope it was useful for others.

Webpack 4 - Module parse failed: You may need an appropriate loader to handle this file type

I have just started to upgrade my aspdotnet core Aurelia project to 3.0 using an upgraded template to the one I used to create the project.
I placed my files (which worked in the previous project) into this new version and I have ended up with a bunch of errors from webpack of which the first is outlined in the heading.
Webpack had also been upgraded. Here is the first error I received..
ERROR in ./ClientApp/public/public/public.css 1:0
Module parse failed: Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type.
> #media (max-width: 767px) {
| /* On small screens, the nav menu spans the full width of the screen. Leave a space for it. */
| .body-content {
# ./ClientApp/public/public/public.html
# ./ClientApp/boot.ts
# ./node_modules/aurelia-webpack-plugin/runtime/empty-entry.js
# multi aurelia-webpack-plugin/runtime/empty-entry aurelia-webpack-plugin/runtime/pal-loader-entry es6-promise/auto aurelia-bootstrapper
Having found the same problem as this it turns out I dont have a double up so its something else..
I also checked out this question which has a very similar heading but I believe the webpack file is Ok as it worked for the basic aurelia files..
This question while similar has a slightly (it would appear) setup to mine in that it has a webpack dev file. To that end here is my package.json with the scripts at the top:
{
"name": "Jobsledger.API",
"private": true,
"version": "0.0.0",
"scripts": {
"lint": "tslint --project tsconfig.json",
"webpack:Debug": "webpack --mode development",
"webpack:Release": "webpack --mode production",
"webpack:watch": "webpack --mode development --watch"
},
"devDependencies": {
"aurelia-animator-css": "^1.0.4",
"aurelia-api": "^3.2.1",
"aurelia-binding": "2.3.1",
"aurelia-bootstrap": "^0.1.20",
"aurelia-bootstrapper": "^2.3.3",
"aurelia-dialog": "^2.0.0-rc.5",
"aurelia-event-aggregator": "^1.0.3",
"aurelia-fetch-client": "^1.8.2",
"aurelia-mask": "^2.0.1",
"aurelia-pal": "^1.8.2",
"aurelia-router": "^1.7.1",
"aurelia-templating": "^1.10.2",
"aurelia-validation": "^1.4.0",
"aurelia-webpack-plugin": "^4.0.0",
"au-table": "^0.1.14",
"awesome-typescript-loader": "^5.2.1",
"bootstrap": "^4.3.1",
"clean-webpack-plugin": "^2.0.2",
"css-loader": "^2.1.1",
"es6-promise": "^4.2.6",
"fetch": "^1.1.0",
"file-loader": "^3.0.1",
"font-awesome": "^4.7.0",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"isomorphic-fetch": "^2.2.1",
"jquery": "^3.4.1",
"mini-css-extract-plugin": "^0.6.0",
"node-sass": "^4.12.0",
"optimize-css-assets-webpack-plugin": "^5.0.1",
"popper.js": "^1.15.0",
"postcss-loader": "^3.0.0",
"sass-loader": "^7.1.0",
"style-loader": "^0.23.1",
"tether": "^1.4.6",
"tslint": "^5.16.0",
"ts-loader": "^6.0.1",
"typescript": "^3.4.5",
"url-loader": "^1.1.2",
"velocity-animate": "^2.0.5",
"webpack": "^4.32.2",
"webpack-cli": "^3.3.2"
}
}
I am thinking I might need modifications to the webpack file re a loader as it mentioned.. before showing the webpack file here is that public.css file thats caused the first error:
#media (max-width: 767px) {
/* On small screens, the nav menu spans the full width of the screen. Leave a space for it. */
.body-content {
padding-top: 50px;
}
}
Now here is the webpack.config.js file
const path = require("path");
const webpack = require("webpack");
const { AureliaPlugin, ModuleDependenciesPlugin, GlobDependenciesPlugin } = require("aurelia-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const bundleOutputDir = "./wwwroot/dist";
module.exports = (env, argv) => {
if ((!argv || !argv.mode) && process.env.ASPNETCORE_ENVIRONMENT === "Development") {
argv = { mode: "development" };
}
console.log("mode =", argv.mode);
const isDevBuild = argv.mode !== "production";
const cssLoaders = ["css-loader", "postcss-loader"];
const scssLoaders = [...cssLoaders, "sass-loader"];
return [{
target: "web",
mode: isDevBuild ? "development" : "production",
entry: { "app": ["es6-promise/auto", "aurelia-bootstrapper"] },
resolve: {
extensions: [".ts", ".js"],
modules: ["ClientApp", "node_modules"]
},
output: {
path: path.resolve(bundleOutputDir),
// Asp.Net JavaScriptServices does not tolerate "/" in public path, see https://github.com/aspnet/JavaScriptServices/issues/1495
publicPath: "dist/",
filename: "[name].[hash].js",
chunkFilename: "[name].[chunkhash].js",
pathinfo: false
},
module: {
rules: [
{ test: /\.(woff|woff2|png|eot|ttf|svg)(\?|$)/, use: { loader: "url-loader", options: { limit: 1, publicPath: "./" } } },
{ test: /\.ts$/i, include: [/ClientApp/], loader: "ts-loader" },
{ test: /\.html$/i, use: "html-loader" },
{ test: /\.css$/i, include: [/node_modules/], issuer: /\.html$/i, use: cssLoaders },
{ test: /\.css$/i, include: [/node_modules/], exclude: [/bootstrap.css$/, /font-awesome.css$/], issuer: [{ not: [{ test: /\.html$/i }] }], use: ["style-loader", ...cssLoaders] },
{ test: /\.css$/, include: [/bootstrap.css$/, /font-awesome.css$/], use: [{ loader: MiniCssExtractPlugin.loader }, ...cssLoaders] },
{ test: /\.scss$/i, issuer: /(\.html|empty-entry\.js)$/i, use: scssLoaders },
{ test: /\.scss$/i, issuer: /\.ts$/i, use: ["style-loader", ...scssLoaders] }
]
},
optimization: {
splitChunks: {
chunks: "all",
// comment the following to avoid creatin a separate bundle for each npm module
maxInitialRequests: Infinity,
minSize: 0,
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name(module) {
// get the name. E.g. node_modules/packageName/not/this/part.js
// or node_modules/packageName
const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
// npm package names are URL-safe, but some servers don't like # symbols
return `npm.${packageName.replace('#', '')}`;
}
}
}
}
},
devtool: isDevBuild ? "source-map" : false,
performance: {
hints: false
},
plugins: [
new CleanWebpackPlugin(),
new webpack.DefinePlugin({ IS_DEV_BUILD: JSON.stringify(isDevBuild) }),
new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery", "window.jQuery": "jquery" }),
new HtmlWebpackPlugin({ template: 'index.ejs', filename: "../../wwwroot/index.html", inject: false, metadata: {}, alwaysWriteToDisk: true }),
new AureliaPlugin({ aureliaApp: "boot" }),
new GlobDependenciesPlugin({ "boot": ["ClientApp/**/*.{ts,html}"] }),
new ModuleDependenciesPlugin({}),
new MiniCssExtractPlugin({
filename: "[name].[hash].css",
chunkFilename: "[name].[chunkhash].css"
})
],
devServer: {
contentBase: "wwwroot/",
compress: true,
writeToDisk: true,
hot: false
}
}];
};
For all the other errors I am essentially getting the same error:
You may need an appropriate loader to handle this file type.
So its a loader of some type..
I am not sure what I need to do to the webpack file to make this work..
Your syntax for the CSS media query is wrong.
You need to write it like:
#media {thing-you-want-to-query} and {case} {
.body-content {
padding-top: 50px;
}
In your case it'd be the screen:
#media screen and (max-width: 767px) {
.body-content {
padding-top: 50px;
}

Antdesign styles not included when re-exporting components with webpack

I'm working on a project that imports components from Antdesign, styles them/add extra props to them,..(extend them) and re-export them. Other projects should then be able to install this project via npm and use the extended components.
A component is structured in a folder like this:
Button
- index.js
index.js contains the import, the extending and the exporting:
import { Button } from 'antd'
Button.foo = bar // just dummy code
export default Button
Then there is an index.js file at component folder level that makes importing easier by exporting all components from there:
export { default as Button} from './Button'
To build into bundle.js I'm using the following webpack config:
const path = require('path')
const nodeExternals = require('webpack-node-externals')
//const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const themes = require('./src/content/theming')
const fs = require('fs');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const lessToJs = require('less-vars-to-js');
const themeVariables = lessToJs(fs.readFileSync(path.join(__dirname, './src/content/theming/test.less'), 'utf8'));
module.exports = env => {
return {
entry: path.resolve(__dirname, 'src/content/components/index.js'),
output: {
path: path.resolve(__dirname, './dist/lib'),
filename: 'index.js'
},
externals: [nodeExternals()],
plugins: [
//new BundleAnalyzerPlugin()
new ExtractTextPlugin('style.css')
],
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/react', { 'plugins': ['#babel/plugin-proposal-class-properties'] }],
plugins: [['import', { 'libraryName': 'antd', 'style': true }]] // `style: true` for less
}
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {}
}
]
},
{
test: /\.less$/,
use: ExtractTextPlugin.extract([
{loader: "css-loader"},
{loader: "less-loader",
options: {
modifyVars: themeVariables,
root: path.resolve(__dirname, './')
}
}
])
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
use: "css-loader"
})
}
]
}
}
}
And this package.json:
{
"name": "new project",
"main": "./dist/lib/index.js",
"files": [
"dist/lib/*"
],
"scripts": {
"build": "./node_modules/.bin/webpack --mode=production"
},
"author": "",
"standard": {
"env": [
"jest"
]
},
"devDependencies": {
"#babel/core": "^7.4.4",
"#babel/plugin-proposal-class-properties": "^7.4.4",
"#babel/preset-env": "^7.4.4",
"#babel/preset-react": "^7.0.0",
"axios": "^0.18.0",
"babel-loader": "^8.0.5",
"babel-plugin-import": "^1.11.0",
"css-loader": "^2.1.1",
"extract-text-webpack-plugin": "4.0.0-beta.0",
"file-loader": "^3.0.1",
"less": "2.7.0",
"less-loader": "^5.0.0",
"less-vars-to-js": "^1.3.0",
"standard": "^12.0.1",
"style-loader": "^0.23.1",
"webpack": "^4.30.0",
"webpack-bundle-analyzer": "^3.3.2",
"webpack-cli": "^3.3.2",
"webpack-node-externals": "^1.7.2"
},
"dependencies": {
"antd": "^3.17.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
}
}
Now, when I run npm run build, it builds correctly, but if I import them in another project, there is not styling.
This is my first time creating a project like this and I just can't get my head around why it is not working. Any help would really be appreciated.
So basically I found the issue myself. In the externals entry in package.json I was calling nodeExternals(). This caused the node_modules folder to be ignored. Removing this included the css in the production build.

React with Webpack - UglifyJSPlugin, Unexpected token: keyword (const)

I am trying to build my React project for production. When I run my production command I get an error about UglifyJSPlugin saying: Unexpected token: keyword (const). Below I have added all my code from my package.json & webpack.config.js file. There are several questions related to this issue but none of them has worked. Any suggestions would be great.
package.json
{
...
"scripts": {
...
"prod": "NODE_ENV=production webpack -p"
},
"dependencies": {
"babel-plugin-add-module-exports": "^0.2.1",
"babel-plugin-react-html-attrs": "^2.0.0",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-stage-0": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
...
"webpack": "^3.4.1",
"webpack-dev-server": "^2.6.1"
},
"devDependencies": {
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"uglify-js": "git://github.com/mishoo/UglifyJS2#harmony-v2.8.22",
"uglifyjs-webpack-plugin": "^0.4.6"
}
}
webpack.config.js
var path = require('path');
var webpack = require('webpack');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
var debug = process.env.NODE_ENV !== 'production';
module.exports = {
context: path.join(__dirname, "src"),
devtool: debug ? "inline-sourcemap" : false,
entry: './js/client.js',
module: {
loaders: [
{
test: /\.js?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
options: {
presets: ['stage-2', 'es2015', 'react'],
plugins: ['react-html-attrs', 'transform-class-properties', 'transform-decorators-legacy']
}
},
{
test: /\.css$/,
loader: ['style-loader/url', 'file-loader']
}
]
},
output: {
path: __dirname + "/src/",
filename: 'client.min.js'
},
plugins: debug ? [] : [
new webpack.optimize.OccurrenceOrderPlugin(),
new UglifyJSPlugin({
mangle: false,
sourceMap: false
})
],
};
.babelrc
{
"presets": [
["stage-2"],
["es2015", {"modules": false}],
["react"]
]
}
UglifyJSPlugin saying that yours js files have keyword const . i think its because of output file is es6. but UglifyJSPlugin needs es5

Categories