Babel setup error: "ERROR in ./src/js/index.js" - javascript

UPDATE: I fixed the issue. Look in answers.
Goal: Set up Babel.
Issue: I run into an error when I use webpack to create a bundle.js file using the command: npm run dev.
screenshot 1 screenshot 2
./src/js/index.js
import num from "./test";
const x = 45;
console.log(`I imported ${num} from test.js - ${x}`);
webpack.config.js:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: ["babel-polyfill", "./src/js/index.js"],
output: {
path: path.resolve(__dirname, "dist"),
filename: "js/bundle.js"
},
devServer: {
contentBase: "./dist"
},
plugins: [
new HtmlWebpackPlugin({
filename: "index.html",
template: "./src/index.html"
})
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
}
};

I fixed the error. Turns out I needed to install new Babel packages.
npm install --save-dev #babel/core #babel/preset-env
npm install --save #babel/polyfill
Replace entry in webpack.config.js with:
entry: ["#babel/polyfill", "./src/js/index.js"],
Replace presets in .babelrc with:
{
"presets": ["#babel/env"]
}

Looks like you're missing babel-core
I think running:
npm install --save-dev babel-core
Should fix it

Related

Webpack generator https://createapp.dev/ fail starting the project

I have found this website which basically is generating a very nice webpack/babel boilerplate structure the problem is that I have some errors when I am trying to run the boilerplate that I do not understand:
> empty-project#1.0.0 start /Users/user.name/Desktop/empty-project
> webpack serve --hot --mode development
[webpack-cli] Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
- configuration.plugins[3] should be one of these:
object { apply, … } | function
-> Plugin of type object or instanceof Function.
Details:
* configuration.plugins[3] should be an object:
object { apply, … }
-> Plugin instance.
* configuration.plugins[3] should be an instance of function.
-> Function acting as plugin.
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! empty-project#1.0.0 start: `webpack serve --hot --mode development`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the empty-project#1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
and this is webpack config file:
const webpack = require('webpack');
const path = require('path');
const CopyPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const config = {
entry: [
'react-hot-loader/patch',
'./src/index.js'
],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader'
]
}
]
},
resolve: {
extensions: [
'.js',
'.jsx'
],
alias: {
'react-dom': '#hot-loader/react-dom'
}
},
devServer: {
contentBase: './dist'
},
plugins: [
new CopyPlugin({
patterns: [{ from: 'src/index.html' }],
}),
new HtmlWebpackPlugin({
templateContent: ({ htmlWebpackPlugin }) => '<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>' + htmlWebpackPlugin.options.title + '</title></head><body><div id=\"app\"></div></body></html>',
filename: 'index.html',
}),,
new BundleAnalyzerPlugin({
analyzerMode: 'static',
openAnalyzer: false,
}),
new MiniCssExtractPlugin(),
new CleanWebpackPlugin()
]
};
module.exports = config;
but you can also check the webpack generator, however I'm not sure why is not working :|
You have double commas after a HtmlWebpackPlugin. Just remove extra one of two ',' signs
should be:
}),
new BundleAnalyzerPlugin({
analyzerMode: 'static',
openAnalyzer: false,
}),
new MiniCssExtractPlugin(),
new CleanWebpackPlugin()
]
};
module.exports = config;
currently:
}),,
new BundleAnalyzerPlugin({
analyzerMode: 'static',
openAnalyzer: false,
}),
new MiniCssExtractPlugin(),
new CleanWebpackPlugin()
]
};
module.exports = config;

I need help adding environment variables to my TypeScript toolchain

I am requesting help setting up the compilation and dev environment for a typescript library. The library should work when consumed by a web app framework and when consumed by a script tag. I am currently using Webpack as a dev server so I can debug and TSC to build (cjs + esm). The issue that prompted this post was having to constantly switch my API strings between http://localhost:8080 to https://production.com. What tools or changes do I need in order to build dev and prod variables into my compilation?
Here is what I'm doing so far:
package.json fragment
"main": "./lib/cjs/index.js",
"module": "./lib/esm/index.js",
"files": [
"lib/**/*",
"README.md"
],
"scripts": {
"build:esm": "tsc -p tsconfig.json --outDir lib/esm --module ES2020 --sourceMap false",
"build:cjs": "tsc -p tsconfig.json --outdir lib/cjs --module commonjs --sourceMap false",
"clean:build": "rimraf lib",
"clean:serve": "rimraf dist",
"build": "rimraf lib && npm run build:esm && npm run build:cjs",
"serve": "rimraf dist && webpack-dev-server"
}
webpack.config.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const SRC = path.resolve(__dirname, 'src')
const ENTRTY = path.resolve(__dirname, 'src', 'debug.ts')
const DIST = path.resolve(__dirname, 'dist')
module.exports = {
mode: 'development',
context: SRC,
entry: ENTRTY,
output: {
path: DIST,
filename: 'index.js',
},
devtool: 'source-map',
devServer: {
contentBase: DIST,
writeToDisk: true,
host: '0.0.0.0',
port: 8080,
https: true,
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin()
],
resolve: {
extensions: ['.ts', '.tsx', '.js']
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
include: [SRC]
}
]
}
}
My toolchain does not currently allow me to do do this:
import Axios from 'axios'
import SocketIO from 'socket.io-client'
export const axios = Axios.create({
baseURL: process.env.SERVER_HTTP_URL, //<-- can't do env-vars with tsc build
withCredentials: true
})
typescript cant not do that, but gulp can do it
const replace = require('gulp-replace');
const { src, dest } = require('gulp');
exports.default = function() {
return src(['*.js'], {base: './'})
.pipe(replace('__XXXX__', 'some variables'))
.pipe(dest('./'));
}

webpack & babel-polyfill: Can't resolve 'core-js/modules/es6.array.map' in source directory

I'm facing this error when I execute webpack:
Module not found: Error: Can't resolve 'core-js/modules/es6.array.map' in '/path/to/project/src'
# ./src/index.ts 1:0-39
index.ts:
console.log([1, 2, 3].map(x => x * x));
.babelrc:
{
"presets": [
[
"#babel/preset-env",
{
"useBuiltIns": "usage"
}
]
]
}
webpack.config.js:
const path = require('path');
module.exports = {
mode: 'development',
entry: './src/index.ts',
devtool: false,
output: {
filename: 'bundle.js',
path: path.join(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.ts$/,
use: [
{ loader: 'babel-loader' },
{ loader: 'ts-loader' }
]
}
]
},
resolve: {
extensions: [
'.ts'
]
}
};
I think it's very weird that the error is trying to resolve the module in src/, not node_modules/.
I tried removing node_modules and package.json and then npm i, but it didn't change the situation.
I also tried another way to use #babel/polyfill described here.
Setting useBuiltIns to 'entry' just increased the number of similar errors. Setting it to false caused different errors.
Module not found: Error: Can't resolve 'core-js/es6' in '/path/to/project/node_modules/#babel/polyfill/lib'
# ./node_modules/#babel/polyfill/lib/index.js 3:0-22
# multi #babel/polyfill ./src/index.ts
ERROR in ./node_modules/#babel/polyfill/lib/index.js
Module not found: Error: Can't resolve 'regenerator-runtime/runtime' in '/path/to/project/node_modules/#babel/polyfill/lib'
# ./node_modules/#babel/polyfill/lib/index.js 23:0-38
# multi #babel/polyfill ./src/index.ts
It seems core-js and regenerator-runtime should be installed in node_modules/#babel/polyfill/. Currently, there are only index.js and noConflict.js in the directory. Do I have to manually install those modules in this directory?
Try to add the following in your resolves -
resolve: {
extensions: [
'.ts',
'.js' // add this
]
}

Dependency Not found even defined in package.json and node_modules

I use vue.js and vue-cli to create a project.
vue init webpack my-project
I am trying to create a component using http://photo-sphere-viewer.js.org/, thus I installed it using
npm install --save photo-sphere-viewer
Then it was downloaded in node_modules and appears in the package.json under dependencies as
"photo-sphere-viewer": "^3.2.3",
And I tried to import in a component, VR-Pano.vue, inside the script tag using
import PhotoSphereViewer from 'photo-sphere-viewer';
And
var PhotoSphereViewer = require('photo-sphere-viewer');
But when I run npm run dev
This dependency was not found:
photo-sphere-viewer in ./~/babel-loader/lib!./~/vue-loader/lib/selector.js?type=script&index=0!./src/components/VR-Pano.vue
I tried:
npm cache clean && npm update -g
Did some researches on webpack, but didn't really know what's going on as I am not too familiar with webpack. I was expecting it to be a simple process, but I suspect something isn't setup properly for my webpack or I did something very stupid.
Here is my webpack.base.conf.js
var path = require('path')
var utils = require('./utils')
var config = require('../config')
var vueLoaderConfig = require('./vue-loader.conf')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
entry: {
app: './src/main.js'
},
// target: 'electron-main',
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'#': resolve('src')
}
},
module: {
rules: [
{
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter')
}
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test')]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('[path][name].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
}
}
I took this debugging opportunity to learn more about npm and webpack.
It looks like the creators of photo-sphere-viewer did not specify where their "main" file was, the file that gets returned when you import or require. I think by default npm looks for index.js at the project root. But a lot of times, package creators put their distribution files under a dist or lib directory. The photo-sphere people did this, but did not specify the location in their package.json. The solution is to add
"main":"./dist/photo-sphere-viewer.min.js"
to the photo-sphere-viewer package.json file. Make sure to add a trailing comma if you're not putting it at the very end. Also i would recommend filing an issue on their Github, this seems like a bug..
Alternatively, you can also do
import PhotoSphereViewer from 'photo-sphere-viewer/dist/photo-sphere-viewer.min.js';

Error: Cannot find module 'extract-text-webpack-plugin'

I've installed extract-text-webpack-plugin using this command in terminal sudo npm install -g extract-text-webpack-plugin and imported in webpack.config.js file, still i'm getting the error.
I also referred this question but didn't found any solution so i've posted new question.
Webpack - extract-text-webpack-plugin Cannot find module
Webpack.config.js file source code:
/* Custom Config */
var ProgramID = '1111';
/* Default Config */
var webpack = require('webpack');
var path = require('path');
var polyfill = require("babel-polyfill");
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var BUILD_DIR = path.resolve(__dirname, 'build/Programs/' + ProgramID);
var APP_DIR = path.resolve(__dirname, 'src/import');
module.exports = {
entry: [
'babel-polyfill',
'webpack-dev-server/client?http://localhost:8080/',
APP_DIR + '/import.js'
],
output: {
path: BUILD_DIR + '/',
filename: '/js/bundle.js',
publicPath: '../Programs/' + ProgramID
},
module: {
loaders: [{
test: /\.jsx?$/,
loaders: ['react-hot', 'babel?presets[]=es2015,presets[]=react,plugins[]=transform-runtime'],
exclude: /node_modules/
}, {
test: /\.css$/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader")
}, {
test: /\.scss$/,
loaders: ["style", "css", "sass"]
}, {
test: /\.(png|woff|woff2|eot|ttf|svg|jpg|gif)$/,
loader: 'file-loader?name=/images/[name].[ext]'
}]
},
plugins: [
new ExtractTextPlugin("style.css"),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
process: function(path, filename) {
if (filename.indexOf('node_modules') === -1) {
path = babelJest.process(path, filename);
path = webpackAlias.process(path, filename);
}
return path;
},
externals: {
"jquery": "jQuery"
}
};
You have installed it for root, but not globally. Add -g flag to install or create package.json with npm init inside you project directory and then do npm install --save extract-text-webpack-plugin

Categories