Import ES6 module from npm package - javascript

I created and published my first npm package. This package contains JS in ES6 syntax and is transpiled to ES5 with webpack and babel.
Now I want to use this npm package but it fails with following error:
ERROR in ./node_modules/chokidar/index.js
Module not found: Error: Can't resolve 'fs' in 'C:\dev\git\open-source\test\node_modules\chokidar'
# ./node_modules/chokidar/index.js 3:9-22
# ./node_modules/watchpack/lib/DirectoryWatcher.js
# ./node_modules/watchpack/lib/watcherManager.js
# ./node_modules/watchpack/lib/watchpack.js
# (webpack)/lib/node/NodeWatchFileSystem.js
# (webpack)/lib/node/NodeEnvironmentPlugin.js
# (webpack)/lib/webpack.js
# ./node_modules/technology-radar/webpack.config.js
# ./sample/app.js
For usage I have the following (minimal) set of files
package.json:
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.0",
"babel-preset-es2015": "^6.24.1",
"webpack": "^3.5.6",
"webpack-dev-server": "^2.4.5",
"babel-polyfill": "^6.26.0",
"html-webpack-plugin": "^2.28.0"
},
"dependencies": {
"d3": "3.5.17",
"technology-radar": "^1.0.3"
}
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
module.exports = {
entry: {
sample: './sample/app.js',
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js'
},
module: {
loaders: [
{
loader: 'babel-loader',
include: [
path.resolve(__dirname, "sample")
],
test: /\.js$/
}
]
},
plugins: [
new UglifyJSPlugin(),
new HtmlWebpackPlugin({
template: 'sample/index.html',
filename: 'index.html',
inject: 'body'
})
],
devtool: "#source-map"
};
sample/app.js
import Radar from 'technology-radar';
var radar = new Radar("#techradarContainer");
radar.render();
I don't know if there is in the usage or in the npm package itself.
The sourcecode of the package is available on github at https://github.com/raman-nbg/techradar. The npm package is available at https://www.npmjs.com/package/technology-radar.
The class which should be export (as defined as entry point in the webpack.config.js of the package) is defined src/Radar.js with export default class Radar { ... }. The entry point is defined as
module.exports = {
entry: {
"technology-radar": "./src/Radar.js",
...
}
...
}

You seem to be misunderstanding how publishing and using packages works.
Ignoring Webpack entirely, a standard npm module has main set to the JS file that is the root of your package, and generally packages published to npm are compiled with Babel before being published. Usually before publishing technology-radar, you'd use a package like babel-cli with
babel src -d lib
to compile everything in the src directory into ES5 inside lib. Then
your package.json#main value should be
"main": "./lib/index.js"
or whichever package is the conceptual root of your package. That could be Radar.js in your case, but it's hard to tell.
Because your main is set to webpack.config.js, when you run Webpack inside your actual application, you are trying to bundle Webpack itself for use on in a browser, which does not work because it is a Node application.
If you've done the above and have a technology-radar package that is already processed with Babel, the configuration of your sample application is pretty much what you already have.

Related

"TypeError: Invalid value used in weak set" while build using webpack

I'm trying to add scss to the project. I want to build css files from scss ones, but I get an error that says "TypeError: Invalid value used in weak set" since I added MiniCssExtractPlugin.
Here's my webpack.config.js:
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const config = {
// TODO: Add common Configuration
module: {},
};
const js = Object.assign({}, config, {
name: 'js',
entry: path.resolve(__dirname, 'index.js'),
output: {
path: path.resolve(__dirname, '../some/path/here'),
filename: 'main.js',
},
});
const scss = Object.assign({}, config, {
name: 'scss',
entry: path.resolve(__dirname, './scss/styles.scss'),
plugins: [
new MiniCssExtractPlugin({
filename: '[name].css',
}),
],
module: {
rules: [
{
test: /\.(s*)css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
{
loader: 'sass-loader',
options: {
implementation: require('sass'),
},
},
],
},
],
},
output: {
path: path.resolve(__dirname, '../some/path/here'),
filename: 'styles.css',
},
});
module.exports = [js, scss];
I googled a lot but didn't find any answers.
I use Node.js v 8.4.0.
Console output (There is more, but I think this is enough):
TypeError: Invalid value used in weak set
at WeakSet.add (native)
at MiniCssExtractPlugin.apply (/path/path/path/path/path/path/path/node_modules/mini-css-extract-plugin/dist/index.js:362:18)
PS: I'm new to webpack, so I'll be glad if you help me to make this code better. The main idea is to keep js compilation the same and add scss compilation. I also want to compile included scss files as separated ones.
PSS: If you need more information, I'll provide some, coz idk what else can be useful.
Maybe the latest mini-css-extract-plugin version has bugs. And I tried to use another version of this package. And its Worked!!!
Remove your last package version:
npm uninstall mini-css-extract-plugin
Download this version 0.9.0 (its worked for me):
npm i --save-dev mini-css-extract-plugin#0.9.0
*optionally (--save-dev)
checkout all versions:
mini-css-extract-plugin/all-versions
This is most likely due to either a bug or an incompatible version of webpack, e.g. upgrading to the current major v2.0.0 releases on webpack 4.
For more information, please check the changelog for breaking changes and fixes.
I think you'll need to downgrade some other plugins as well. I was following a tutorial when I had the same error. This is what worked for me:
{
"name": "recipe-blocks",
"scripts": {
"dev": "cross-env BABEL_ENV=default webpack --watch",
"build": "cross-env BABEL_ENV=default NODE_ENV=production webpack -p"
},
"main": "index.js",
"devDependencies": {
"#babel/core": "^7.0.0",
"#babel/plugin-transform-react-jsx": "^7.2.0",
"#wordpress/babel-preset-default": "^3.0.1",
"babel-loader": "^8.0.4",
"classnames": "^2.2.6",
"cross-env": "^5.1.5",
"css-loader": "^2.1.1",
"mini-css-extract-plugin": "^0.6.0",
"node-sass": "^4.12.0",
"raw-loader": "^2.0.0",
"sass-loader": "^7.1.0",
"webpack": "^4.26.1",
"webpack-cli": "^3.1.2"
},
"version": "1.0.0",
"license": "MIT"
}
Then Run:
npm install
npm run dev

Cannot find module 'path'

I'm attempting to learn Typescript and thought I should also make my webpack config in .ts. This is my webpack.config.ts:
import * as webpack from 'webpack';
import * as path from 'path';
const config: webpack.Configuration = {
entry: path.resolve('src/main.ts'),
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.tsx', '.ts', '.js']
},
output: {
filename: 'index.js',
path: path.resolve( 'dist')
}
}
export default config;
As well as my package.json:
"main": "index.js",
"scripts": {
"prebuild": "rimraf dist",
"build": "webpack --config devtools/webpack.config.ts --display-error-details",
"post-build": "webpack-dev-server --config devtools/webpack.config.ts --mode development"
},
"author": "",
"license": "ISC",
"devDependencies": {
"ts-loader": "^4.0.1",
"ts-node": "^5.0.1",
"typescript": "^2.7.2",
"webpack": "^4.1.1",
"webpack-cli": "^2.0.12",
"webpack-dev-server": "^3.1.1"
}
}
The error I get when running npm run build is:
TS2307: Cannot find module 'path'
I have also tried requiring path, but then I get a different error saying it cant find module require.
What seems to be the issue?
This should help
npm i #types/node -D
Typescript needs typings for any module, except if that module is not written in typescript.
Using
"types": ["node"]
in tsconfig.json as mentioned in the comments, solved the issue for me.
I had to do all this
[VS Code][Terminal] upgrade typescript: npm i typescript/#latest -g
[VS Code][Terminal] install node types: npm i #types/node --save-dev
[VS Code][tsconfig.json] add types: "compilerOptions": {types:["node"]}
[VS Code][Explorer] delete package-lock.json and node_modules
[VS Code][Terminal] install: npm install
[VS Code] Restart VS Code
[VS Code][Terminal] test: tsc
Try using require syntax rather than import & change webpack.config.ts to the following code
webpack.config.ts
const webpack = require('webpack');
const path = require('path');
const config: webpack.Configuration = {
entry: path.resolve('src/main.ts'),
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.tsx', '.ts', '.js']
},
output: {
filename: 'index.js',
path: path.resolve( 'dist')
}
}
module.exports = config;
And then run npm run build
First of all no need of .ts extension for webpack config file. Its just internal purpose for building the bundle. Use normal .js file.
Webpack is not ran by browser, its by Node Js which runs webpack module and make bundle as per config.
Now Node Js understand its own module system is which is require
So it would be like below: require in below is Node Js module importing syntax.
const webpack = require('webpack');
const path = require('path');

Webpack looking for index in datatables extension which has none

What I am trying to do is use datatables. I get the error:
ERROR in ./index.js
Module not found: Error: Can't resolve 'datatables.net-dt' in path/src
for all the datatables requires when I try to webpack it. I ran webpack with --display-error-details and found the problem to be that it is looking in the datatable directories for an index file of some sort. e.g.
Field 'browser' doesn't contain a valid alias configuration
path/node_modules/datatables.net-colreorder-dt/index doesn't exist
.js
Field 'browser' doesn't contain a valid alias configuration
path/node_modules/datatables.net-colreorder-dt/index.js doesn't exist
.json
Field 'browser' doesn't contain a valid alias configuration
path/node_modules/datatables.net-colreorder-dt/index.json doesn't exist
I don't understand why it is looking for the index. I have followed all the documentation I can find on webpack and datatables and according to the datatables download section I should only have to add the packages (which I have done) and add the require's part and it should work.
I have looked at the repos for datatables and its extensions and there is no index in any of them. I've googled this in every which way possible and can't find any answer so I'm hoping someone here might have an idea as I have tried many different things which either didn't work or produced even more errors.
This is my index.js
require('./index.html');
var AWS = require('aws-sdk');
require( 'datatables.net-dt' )();
require( 'datatables.net-buttons-dt' )();
require( 'datatables.net-buttons/js/buttons.print.js' )();
require( 'datatables.net-colreorder-dt' )();
require( 'datatables.net-fixedheader-dt' )();
require( 'datatables.net-rowgroup-dt' )();
No code after the requires runs so I haven't included it.
This is my package.json
{
"name": "TestCode",
"version": "1.0.0",
"description": "Test",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
"keywords": [],
"author": " ",
"license": "ISC",
"dependencies": {
"aws-sdk": "^2.116.0",
"datatables.net-buttons-dt": "^1.4.2",
"datatables.net-colreorder-dt": "^1.4.1",
"datatables.net-dt": "^1.10.16",
"datatables.net-fixedheader-dt": "^3.1.3",
"datatables.net-rowgroup-dt": "^1.0.2",
"jquery": "^3.2.1",
"raw-loader": "^0.5.1"
},
"devDependencies": {
"html-webpack-plugin": "^2.30.1",
"json-loader": "^0.5.7",
"webpack": "^3.6.0",
"webpack-dev-server": "^2.9.1"
},
}
and this is my webpack.config.js
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
devtool: 'cheap-module-eval-source-map',
context: path.resolve(__dirname, 'src'),
entry: './index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
devServer: {
contentBase: path.resolve(__dirname, 'src')
},
module: {
loaders: [
{
test: /\.json$/,
loaders: ['json']
},
{
test: /\.html$/,
loader: ['raw-loader']
}
]
},
resolveLoader: {
moduleExtensions: ['-loader']
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
template: './index.html'
})
]
};
First off, your require statements don't need an extra () at the end. require('module'); is fine.
Secondly, you have one statement with a .js extension. It shouldn't be there because you're requiring modules, not files.
Finally, to the solution that fixes your problem: You're missing a resolve field in your webpack.config.js. When you leave the resolve field out, all of the require() statements are looking for modules inside your given context folder, which in your case is the source (src) folder (defaults to root folder when not defined).
To solve this problem, add something like the following to your webpack.config.js:
resolve: {
modules: [
path.resolve('./node_modules')
]
}
Or wherever your node modules may be.
The reason webpack is looking for the index, is because it's default. It couldn't find the module you referenced, so it's looking for an index file instead. The reason you're getting multiple errors on the same import is because it's looking for more than one extension.
The extensions default to extensions: [".js", ".json"]. This is why you see the .js and .json in your error logs. (btw this is also why you can leave extensions out of your require() statements)
If you need more help understanding webpack feel free to ask, or check out https://webpack.js.org/configuration/resolve/ for the documentation on the resolve options for more stuff you can do with resolving your modules.

Node.js + Typescript + Webpack = Module not found

I'm new with Webpack, Node.js and Typescript and I'm having trouble configuring my dev enviroment.
When running webpack to compile my src/server.ts to generate the /server/bundle.js I'm getting this error:
ERROR in ./src/server.ts
Module not found: Error: Can't resolve 'hapi' in '/Volumes/Dados/giovane/dev/studio-hikari/nodang/nodang-api/src'
# ./src/server.ts 3:11-26
The architecture of the project is:
The src/server.ts:
import * as Hapi from 'hapi';
const server = new Hapi.Server();
The webpack.config.js:
const path = require('path');
module.exports = {
entry: './src/server.ts',
output: {
filename: './server/bundle.js'
},
resolve: {
extensions: ['.ts'],
modules: [
path.resolve('src'),
path.resolve('node_modules')
]
},
module: {
loaders: [
{
test: /.ts$/,
loader: 'awesome-typescript-loader'
}
]
}
};
The package.json:
{
"name": "nodang-api",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"compile": "webpack --progress --watch",
"serve": "node-dev server/bundle.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"#types/hapi": "^16.0.0",
"lodash": "^4.17.4"
},
"devDependencies": {
"awesome-typescript-loader": "^3.0.8",
"tsd": "^0.6.5",
"typescript": "^2.2.1",
"webpack": "^2.2.1"
}
}
OBS: It's webpack 2
UPDATE
After installing hapi and adding .js to webpack's resolve extentions and node as webpack's target I'm getting this erros with hapi modules:
ERROR in ./~/hapi/lib/server.js
Module not found: Error: Can't resolve 'catbox' in '/Volumes/Dados/giovane/dev/studio-hikari/nodang/nodang-api/node_modules/hapi/lib'
# ./~/hapi/lib/server.js 5:15-32
# ./~/hapi/lib/index.js
# ./src/server.ts
ERROR in ./~/hapi/lib/server.js
Module not found: Error: Can't resolve 'catbox-memory' in '/Volumes/Dados/giovane/dev/studio-hikari/nodang/nodang-api/node_modules/hapi/lib'
# ./~/hapi/lib/server.js 6:21-45
# ./~/hapi/lib/index.js
# ./src/server.ts
You did not install hapi. #types/hapi are just the type definitions that TypeScript uses for the library, but not the actual library itself. So you need to add hapi as well:
npm install --save hapi
Once you've installed it, the module can be found, although you'll get a new error that ./server could not be resolved in hapi/lib/index.js and that's because you configure resolve.extensions to only include .ts, but the library makes use of Node automatically resolving .js when leaving off the extension. So you also need to include .js in the extensions:
extensions: ['.ts', '.js'],
After also resolving this issue, you'll be faced with another one, namely that Node built-in modules like fs can't be resolved. By default webpack builds for the web, so the Node built-in modules are not available. But you can change that by setting the target option in your webpack config to node:
target: 'node'
Edit
You're having trouble with other node_modules because you only use the top level node_modules, instead you want to always fall back to the regular module resolution of node_modules, so the resolve.modules should look like this:
modules: [
path.resolve('src'),
'node_modules'
]

How to add a separate CSS file for .scss files using webpack?

I have a pretty simple JavaScript app I'm compiling using Webpack. I have the application splitting into two separate bundles now - App and Vendor. App contains my custom code while the vendor files contains the frameworks.
The app bundle contains all the JavaScript in my app directory, but there are also some Sass files in there as well. I'm trying to get those to compile into a separate CSS bundle file.
Through some research, I figured out I needed to use the extract-text-webpack-plugin with a webpack Sass compiler and style loaders.
Here is my webpack.config file:
var webpack = require('webpack')
var ExtractTextPlugin = require("extract-text-webpack-plugin")
module.exports = {
context: __dirname + '/app',
entry: {
app: './app.module.js',
vendor: ['angular','angular-route']
},
output: {
path: __dirname + '/bundle',
filename: 'app.bundle.js'
},
module: {
loaders: [
{ test: /\.scss$/, loader: ExtractTextPlugin.extract("style- loader", "css-loader") }
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin(/* chunkName= */'vendor', /* filename= */'vendor.bundle.js'),
new ExtractTextPlugin("styles.css")
]
}
I have the following dependencies installed using npm:
"css-loader": "^0.23.1",
"extract-text-webpack-plugin": "^1.0.1",
"node-sass": "^3.8.0",
"sass-loader": "^4.0.0",
"style-loader": "^0.13.1",
"webpack": "^1.13.1"
The problem is when I bundle using webpack, I get the following error:
Module not found: Error: Cannot resolve 'file' or 'directory' ./../node_modules/css-loader/index.js
And
Module not found: Error: Cannot resolve 'file' or 'directory' ./../node_modules/style-loader/addStyles.js
I'm only including one sass file in my main application file at the moment. In my main app.js file, I have: require('./styles.scss') Any ideas why this is happening?
To those of you that may be having the same issue, and you're running Windows, the following solution worked for me:
At the top of our webpack.config add the following:
var path = require('path');
Then change where you define your context to:
context: path.resolve(__dirname, "folder_name")

Categories