Webpack on the backend: missing exports - javascript

I'm trying to use webpack on the backend to transpile this code (called sub.js):
export const foo1 = () => {
console.log("I'm foo1");
};
console.log('loaded');
I can compile it and then import it fine. On import (require) I see the 'loaded', but the imported object is empty and in particular has no function foo1.
This is my webpack.config.js:
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: `./sub.js`,
module: {
rules: [{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
plugins: [
'#babel/plugin-proposal-class-properties'
]
},
}],
},
resolve: {
extensions: ['*', '.js', '.jsx'],
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'backend.js'
},
mode: 'production',
};
My package.json:
{
"name": "sub",
"version": "1.0.0",
"description": "",
"main": "dist/backend.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.13.8",
"#babel/plugin-proposal-class-properties": "^7.13.0",
"#babel/preset-env": "^7.13.9",
"#babel/preset-react": "^7.12.10",
"babel-loader": "^8.2.2",
"webpack": "^5.65.0",
"webpack-cli": "^4.9.1"
}
}
I test using:
> npx webpack && node --eval "r = require('./dist/backend.js'); console.log(r);"
asset backend.js 45 bytes [emitted] [minimized] (name: main)
runtime modules 396 bytes 2 modules
./sub.js 204 bytes [built] [code generated]
webpack 5.65.0 compiled successfully in 250 ms
loaded
{}
I was expecting to see:
loaded
{foo1: [Function]}
or similar.

Found the issue. Apparently you need to explicitly declare exported libraries in the output. Now that I've added this:
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'backend.js',
library: {
type: 'commonjs-module',
},
},
I get:
> npx webpack && node --eval "r = require('./dist/backend.js'); console.log(r);"
asset backend.js 192 bytes [emitted] [minimized] (name: main)
./sub.js 323 bytes [built] [code generated]
webpack 5.65.0 compiled successfully in 275 ms
loaded
{ foo1: [Function] }
as expected.
For reference https://webpack.js.org/configuration/output/#outputlibrary.

Related

Changes to imported files in webpack library not output during watch

I have a small JS project compiled by webpack 5.26 with the following structure:
>dist
>src
>js
>classes
carousel.js
navBar.js
neso.src.js
>scss
When running npm run watch, changes made in navBar.js or carousel.js are not outputted after the initial build. Changes made in files in the scss folder and neso.src.js are outputted.
Command line output on these occurances looks like this:
assets by status 72.1 KiB [cached] 1 asset
cached modules 56.1 KiB (javascript) 997 bytes (runtime) [cached] 16 modules
webpack 5.26.0 compiled successfully in 131 ms
I've tried adding the watchOptions property and changing the entry property value in my webpack.config.js. I've also tried changing the import/export declarations in neso.src.js but nothing helped and changes in classes files still aren't being output on watch. Please can you advise how to achieve this.
package.json
{
"name": "Neso-test",
"version": "0.0.1",
"description": "",
"private": true,
"main": "dist/neso.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "cross-env NODE_ENV=development webpack",
"build": "cross-env NODE_ENV=production webpack",
"watch": "cross-env NODE_ENV=development webpack --watch --progress",
"serve": "cross-env NODE_ENV=development webpack serve"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.13.10",
"#babel/preset-env": "^7.13.10",
"babel-loader": "^8.2.2",
"cross-env": "^7.0.3",
"css-loader": "^5.1.3",
"mini-css-extract-plugin": "^1.3.9",
"postcss": "^8.2.8",
"postcss-loader": "^5.2.0",
"postcss-preset-env": "^6.7.0",
"sass": "^1.32.8",
"sass-loader": "^11.0.1",
"style-loader": "^2.0.0",
"webpack": "^5.26.0",
"webpack-cli": "^4.5.0"
}
}
webpack.config.json
const path = require("path");
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const mode = process.env.NODE_ENV === 'production' ? 'production' : 'development';
module.exports = {
mode: mode,
entry: path.resolve(__dirname, "src/js/neso-src.js"),
output: {
path: path.resolve(__dirname, "dist"),
filename: "neso.js",
library: "Neso",
libraryTarget: "umd",
},
devtool: "source-map",
devServer: {
contentBase: "./dist"
},
module: {
rules: [
{
test: /\.(js)$/,
exclude: /node_modules/,
use: "babel-loader",
},
{
test: /\.(s[ac]|c)ss$/i, // This regex adds support for .scss, .sass and .css file types
use: [
mode === 'development' ? "style-loader" : MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader",
"postcss-loader"
],
}
],
},
plugins: [
new MiniCssExtractPlugin()
],
watchOptions: {
aggregateTimeout: 200,
poll: 1000,
},
}
The code in neso-src.js had this import statement:
import NavBar from './classes/NavBar.js';
and the referenced filename was actually navBar.js.
Changing the import statement to import NavBar from './classes/navBar.js'; worked and changes in that file now trigger a recomplile. (Uppercase 'N' to lowercase 'n').
Real credit goes to this answer which pointed me in the right direction.

Webpack doesn't transpile to ES5

I have already done some research and tried different configurations of webpack. However, webpack won't compile my ES5+ code to ES5. In my node_modules directory I have a bunch of babel directories:
babel-preset-env
babel-preset-es2015
babel-core
babel-helpers
babel-helper-{lotsOfDifferentDirectories}
babel-plugin-{lotsOfDifferentDirectories}
#babel
#babel/core
#babel/preset-env
and many many more...
webpack.config.js
const path = require('path');
module.exports = {
entry: {
app: "./_assets/js/src/example.js"
},
mode: "development",
output: {
path: path.resolve(__dirname, "_assets/js/build"),
filename: "exampleBundle.js"
},
module: {
rules: [{
test: /\.js?$/,
exclude: /node_modules/,
loader: "babel-loader",
query: {
presets: ["#babel/preset-env"]
}
}]
}
}
package.json
{
"name": "jkk-onepager",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
"repository": {
"type": "git",
"url": "http://10.8.1.1:850/root/jkk-onepager.git"
},
"author": "",
"license": "ISC",
"dependencies": {
"#babel/core": "^7.3.4",
"#babel/preset-env": "^7.3.4",
"babel-core": "^6.26.3",
"babel-loader": "^8.0.5",
"babel-preset-es2015": "^6.24.1",
"webpack": "^4.29.6",
"webpack-dev-server": "^3.2.1"
},
"devDependencies": {
"babel-preset-env": "^1.7.0",
"webpack-cli": "^3.2.3"
}
}
src/example.js
let testArray = [1,2,3,4,5];
testArray.forEach( item => {
console.log(item);
})
part of exampleBundle.js
/***/ "./_assets/js/src/example.js":
/*!***********************************!*\
!*** ./_assets/js/src/example.js ***!
\***********************************/
/*! no static exports found */
/***/ (function(module, exports) {
eval("var testArray = [1, 2, 3, 4, 5];\ntestArray.forEach(function (item) {\n console.log(item);\n});\n\n//# sourceURL=webpack:///./_assets/js/src/example.js?");
/***/ })
/******/ });
Console output after I run npm run build
Hash: 70c0ea4134e6e46211b5
Version: webpack 4.29.6
Time: 896ms
Built at: 2019-03-21 11:28:05
Asset Size Chunks Chunk Names
exampleBundle.js 3.94 KiB app [emitted] app
Entrypoint app = exampleBundle.js
[./_assets/js/src/example.js] 93 bytes {app} [built]
Has somebody else faced this issue before? I have tried out every suggestion I could find in articles about this issue, but it didn't help. Any idea how to fix this?

Module parse failed: Unexpected token

Hey Getting the error below I run the webpack command:
$> webpack --mode "development"
stack trace:
Version: webpack 4.17.2
Time: 1357ms
Built at: 09/10/2018 8:13:26 PM
Asset Size Chunks Chunk Names
bundle.js 1.37 MiB main [emitted] main
Entrypoint main = bundle.js
[0] fs (ignored) 15 bytes {main} [built]
[./node_modules/css-loader/index.js!./wwwroot/Source/Styles/app.css] ./node_modules/css-loader!./wwwroot/Source/Styles/app.css 165 bytes {main} [built]
[./node_modules/css-loader/index.js!./wwwroot/Source/Styles/site.css] ./node_modules/css-loader!./wwwroot/Source/Styles/site.css 207 bytes {main} [built]
[./node_modules/webpack/buildin/global.js] (webpack)/buildin/global.js 509 bytes {main} [built]
[./node_modules/webpack/buildin/module.js] (webpack)/buildin/module.js 519 bytes {main} [built]
[./wwwroot/Source/Script/app.ts] 221 bytes {main} [built]
[./wwwroot/Source/Script/site.ts] 274 bytes {main} [built] [failed] [1 error]
[./wwwroot/Source/Styles/app.css] 1.06 KiB {main} [built]
[./wwwroot/Source/Styles/site.css] 1.07 KiB {main} [built]
+ 30 hidden modules
ERROR in ./wwwroot/Source/Script/site.ts 25:8
Module parse failed: Unexpected token (25:8)
You may need an appropriate loader to handle this file type.
|
| class Animal {
> name: string;
| constructor(theName: string) { this.name = theName; }
| move(distanceInMeters: number = 0) {
# ./wwwroot/Source/Script/app.ts 4:0-16
It seems it does not recognize the properties in any of my classes when transpiling.
** ts code **
class Animal {
name: string;
constructor(theName: string) { this.name = theName; }
move(distanceInMeters: number = 0) {
console.log(`${this.name} moved
${distanceInMeters}m.`);
}
}
tsconfig
{
"compilerOptions": {
"outDir": "./app/",
"noImplicitAny": true,
"module": "es6",
"target": "es5",
"allowJs": true,
"sourceMap": true
}
}
package.json
{
"name": "ExposureAPI",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"wbp": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.0.0",
"#babel/preset-env": "^7.0.0",
"#types/jquery": "^3.3.6",
"#types/underscore": "^1.8.9",
"babel-loader": "^8.0.2",
"bootstrap": "^4.1.3",
"css-loader": "^1.0.0",
"gulp-babel": "^8.0.0",
"jquery": "^3.3.1",
"popper.js": "^1.14.4",
"style-loader": "^0.22.1",
"ts-loader": "^4.5.0",
"typescript": "^3.0.1",
"underscore": "^1.9.1",
"webpack": "^4.17.2",
"webpack-cli": "^3.1.0"
},
"dependencies": {
"#types/simplemde": "^1.11.7",
"simplemde": "^1.11.2"
}
}
webpack.config.js
const path = require('path');
module.exports = {
entry: './wwwroot/Source/Script/app.ts',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
devtool: 'inline-source-map'
}
]
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ]
},
output: {
path: path.resolve(__dirname, 'wwwroot/App'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.css$/,
exclude: ['node_modules'],
use: [
{ loader: "style-loader" },
{ loader: "css-loader" }
]
}]
}
};
Thanks
Apparently it happened because you have two module properties in the webpack config object.
Given JS objects can only hold one value per key - one value would be lost. And in this particular case the latter was overwriting the former, so webpack ended up configured without typescript loader config at all.

'npm run build' by webpack, I got an error...help me

I got following error when I was transpiling the webpack.
**error message**
$ npm run build
> webpack
Hash: d3c6c864b2d5118a08d7
Version: webpack 4.8.3
Time: 399ms
Built at: 2018-06-04 20:51:32
1 asset
Entrypoint main = bundle.js
[0] ./src/index.js 249 bytes {0} [built] [failed] [1 error]
ERROR in ./src/index.js
Module parse failed: Unexpected token (5:16)
You may need an appropriate loader to handle this file type.
| import App from "../component/chatapp";
|
| ReactDOM.render(<App />, document.getElementById("root"));
|
Child html-webpack-plugin for "index.html":
1 asset
Entrypoint undefined = index.html
[0] (webpack)/buildin/module.js 519 bytes {0} [built]
[1] (webpack)/buildin/global.js 509 bytes {0} [built]
+ 2 hidden modules
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! website#1.0.0 build: `webpack`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the website#1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\bca19\AppData\Roaming\npm-cache\_logs\2018-06-04T11_51_32_160Z-debug.log
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: path.resolve(path.resolve(__dirname, "src"), "index.js"),
output: {
path: path.resolve(__dirname, "public"),
filename: 'bundle.js'
},
mode: 'production',
resolve: {
extensions: ['js', '.jsx']
},
module: {
rules: [{
test: /\.(js|jsx)$/,
loader: "babel-loader",
include: [
path.resolve(__dirname + "component"),
path.resolve(__dirname + "src")
],
exclude: [
path.resolve(__dirname, "node_modules")
],
query: {
presets: ["react", "es2015"]
}
}, {
test: /\.css$/,
use: ExtractTextPlugin.extract({
use: "css-loader"
})
}, {
test: /\.scss$/,
use: ExtractTextPlugin.extract({
use: [
"css-loader",
"sass-loader"
]
})
}]
},
plugins: [
new HtmlWebpackPlugin({
title: "ę´‘talk",
filename: path.resolve(__dirname, "public", "index.html")
})
],
devtool: "inline-source-map",
devServer: {
contenBase: path.resolve(__dirname, "public"),
compress: true,
port: 3000
}
};
package.json
{
"name": "website",
"version": "1.0.0",
"description": "test website",
"main": "index.js",
"scripts": {
"build": "webpack",
"watch": "webpack --watch",
"start": "webpack-dev-server --hot --inline"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.16.3",
"express-handlebars": "^3.0.0",
"jquery": "^3.3.1",
"path": "^0.12.7",
"react": "^16.3.2",
"react-dom": "^16.3.2",
"socket.io": "^2.1.1"
},
"devDependencies": {
"babel": "^6.23.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"copy-webpack-plugin": "^4.5.1",
"css-loader": "^0.28.11",
"extract-text-webpack-plugin": "^3.0.2",
"html-webpack-plugin": "^3.2.0",
"sass-loader": "^7.0.1",
"webpack": "^4.8.3",
"webpack-cli": "^2.1.3",
"webpack-dev-server": "^3.1.4",
"zombie": "^6.1.2"
},
"babel": {
"presets": [
"es2015"
]
}
}
index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "../component/chatapp";
ReactDOM.render(<App />, document.getElementById("root"));
chatapp.js
import React from "react";
class ChatApp extends React.Component {
render() {
return (
<div>mission success</div>
);
}
}
export default ChatApp;
I don't know why my codes are not working.
Maybe the path of the rule is wrong.Try
include: [
path.resolve(__dirname , "component"),
path.resolve(__dirname ,"src")
],
You are missing a dot before the file extension.
extensions: ['.js', '.jsx']

React, Webpack: bundle.js is not generated

Edit: The reason was that I was running webpack-dev-server, when running just webpack it worked.
I am using React and Webpack. The bundle.js is not generated. I found this question on SO that brought up the same issue, but I seem to have the required dependencies installed. Here is my webpack.config.js:
var webpack = require('webpack');
module.exports = {
entry: [
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/only-dev-server',
'./src/index.js'
],
module: {
loaders: [{
test: /\.js?$/,
exclude: /node_modules/,
loader: 'react-hot!babel'
}]
},
resolve: {
extensions: ['', '.js']
},
output: {
path: 'dist',
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: './dist',
hot: true
},
plugins: [
new webpack.HotModuleReplacementPlugin()
]
};
Here is my package.json:
{
"name": "plump",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/fiskpatte/plump.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"babel": {
"presets": [
"es2015",
"react"
]
},
"bugs": {
"url": "https://github.com/fiskpatte/plump/issues"
},
"homepage": "https://github.com/fiskpatte/plump#readme",
"devDependencies": {
"babel-core": "^6.8.0",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.5.0",
"react-hot-loader": "^1.3.0",
"webpack": "^1.13.0",
"webpack-dev-server": "^1.14.1"
},
"dependencies": {
"history": "^2.1.1",
"react": "^15.0.1",
"react-dom": "^15.0.1",
"react-router": "^2.4.0"
}
}
Any idea?
Edit. Output when running webpack:
Asset Size Chunks Chunk Names
bundle.js 1.19 MB 0 [emitted] main
0.63b359d04fe48d6168fa.hot-update.js 27.9 kB 0 [emitted] main
63b359d04fe48d6168fa.hot-update.json 36 bytes [emitted]
chunk {0} bundle.js, 0.63b359d04fe48d6168fa.hot-update.js (main) 1.11 MB [rendered]
[318] ./src/components/LoginPage.js 8.93 kB {0} [built]
[322] ./src/components/Lobby.js 12.2 kB {0} [built]
[323] ./src/components/SignUp.js 5.6 kB {0} [built]
[324] ./src/pages/Game.js 27.3 kB {0} [built]
+ 321 hidden modules
webpack: bundle is now VALID.
Theres probably something wrong with the output path .. can you try replacing the output path to ./dist
It is due to missing of some key-value pairs in scripts of package.json. Replace your scripts object with the following:
"scripts": {
"start": "npm run build",
"build": "webpack -p && webpack-dev-server"
},
"-p" means specially for production evnvironment of webpack.config.js. Then run this cmd: $ npm start
$ npm start will invoke npm run build cmd which in turn will invoke "webpack -p && webpack-dev-server"

Categories