I'm new to React.js and I'm trying to learn from the tutorials on tutorialspoint but I faced error. Here is the error on console when I execute npm start command:
C:\Users\HP\Desktop\reactApp1> npm start
> reactapp1#1.0.0 start C:\Users\HP\Desktop\reactApp1.
> webpack-dev-server --hot
The CLI moved into a separate package: webpack-cli.
Please install .webpack-cli. in addition to webpack itself to use the CLI.
-> When using npm: npm install webpack-cli -D
-> When using yarn: yarn add webpack-cli -D
module.js:540
throw err;
Error: Cannot find module .webpack-cli/bin/config-yargs.
at Function.Module._resolveFilenam (module.js:538:15)
at Function.Module. load (module.j5:668:25)
at Module.require (module.js,587.17)
at require (internal/module.js:11:18)
at Object•<anonymous> (C:\Users\HP\Desktop\reactApp1\node_modules\webpack-dev-server\bin\webpack-dev-server.js:65:1)
at Module. compile (module.js:663:30)
at Object.Module. extensions. .js (module.js:656:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:699:12)
at Function.Module. load (modul.js:691:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! reactapp#1.0.0 start: `webpack-dev-server --hot`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the reactapp#1.0.0 start 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\HP\AppData\Roaming\npm-cache\_logs\2018-03-06T05_29_08_833Z-debug.log
package.json
{
"name": "reactapp1",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --hot"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.26.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"webpack": "^4.0.1",
"webpack-dev-server": "^3.1.0"
},
"devDependencies": {
"babel-loader": "^7.1.3"
}
}
webpack.config.js
var config = {
entry: './main.js',
output: {
path:'./',
filename: 'index.js',
},
devServer: {
inline: true,
port: 8090
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
module.exports = config;
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App />, document.getElementById('app'));
App.jsx
import React from 'react';
class App extends React.Component {
render() {
return (
<div>
Hello World!!!
</div>
);
}
}
export default App;
index.html
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>React App</title>
</head>
<body>
<div id = "app"></div>
<script src = "index.js"></script>
</body>
</html>
I went through the same example and faced the same issue. So following the above answers I first ran this command -
npm install -g webpack-cli --save-dev
Nothing happened and was still facing the same issue.
Then I ran this command -
npm install webpack-cli --save-dev
The issue was solved but I was getting another error.
Turns out in the new Webpack version they have changed the module attributes also. So you need to make change in the webpack.config.js file also.
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
}
So basically loaders is replaced by rules inside the module object.
I made this change and it worked for me.
Hope it helps other people who are following this tutorial.
To resolve the Invalid configuration object issue, I referred to this answer.
https://stackoverflow.com/a/42482079/5892553
In webpack 3, webpack itself and the CLI for it used to be in the same package, but in version 4, they've separated the two to manage each of them better.
To solve your issue, install the webpack-cli package as the error suggests by running npm install webpack-cli --save-dev on the command line, same as you would any other package.
Was having the same problem, and no luck with the above solutions - I tried installing webpack-cli globally as well as locally and this worked.
npm install -g webpack-cli --save-dev
This fixed it for me. At least enough to perform webpack --mode development.
Step1: First run
npm i webpack webpack-dev-server webpack-cli --save-dev
Step2: Loaders are replaced with rules so change code in your webpack.config.j. Let's change your webpack.config.js file:
var config = {
entry: './main.js',
output: {
path:'./',
filename: 'index.js',
},
devServer: {
inline: true,
port: 8090
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
module.exports = config;
Step3: Now go to your package.json file and make some changes in your scripts option:
"scripts": {
"start": "webpack-dev-server --mode development --open --hot",
"build": "webpack --mode production"
},
Step4: Now run
npm start
in console
Solved for Webpack 4 - I hope it works for webpack 2 onwards
Install webpack-cli globally too by using this command
npm i -g webpack-cli
So in total you need to run two following commands one for local and other for install CLI globally respectively.
npm i -D webpack-cli
npm i -g webpack-cli
it works for me I hope it will work for you too :)
I solved the problem with this.
npm i webpack-cli #webpack-cli/init
npx webpack-cli init
Hope to help 1
You need install webpack server, not webpack-cli. Have a look at the 2nd point in this blog post.
Try npm i -g webpack#2.2.1.
If you want to use webpack-dev-server, you need to install webpack and webpack-cli first. webpack is a module which store compiler and, webpack-cli is command-line-interface to run it. Otherwise, if you prefer webpack-command, a much more light-weight version of webpack-cli, you may need to install webpack and webpack-serve!
The error console is simply telling you how to resolve the issue. Seems like webpack module is dependent on webpack-cli module. To resolve the issue, just run the command npm install webpack-cli --save. it would just work fine.
Related
Information
I have an application (reactjs) that run with docker, It use webpack but at start it crash saying that html-loader can't be resolve. I install it but when I rerun docker, It continue to say that.
Error message
Html Webpack Plugin:
Error: Child compilation failed:
Entry module not found: Error: Can't resolve 'html-loader' in '/usr/src/app/client':
Error: Can't resolve 'html-loader' in '/usr/src/app/client'
- compiler.js:153 childCompiler.runAsChild
[client]/[html-webpack-plugin]/lib/compiler.js:153:18
- Compiler.js:306 compile
[client]/[webpack]/lib/Compiler.js:306:11
- Compiler.js:631 hooks.afterCompile.callAsync.err
[client]/[webpack]/lib/Compiler.js:631:15
- Hook.js:154 AsyncSeriesHook.lazyCompileHook
[client]/[tapable]/lib/Hook.js:154:20
- Compiler.js:628 compilation.seal.err
[client]/[webpack]/lib/Compiler.js:628:31
- Hook.js:154 AsyncSeriesHook.lazyCompileHook
[client]/[tapable]/lib/Hook.js:154:20
- Compilation.js:1329 hooks.optimizeAssets.callAsync.err
[client]/[webpack]/lib/Compilation.js:1329:35
package.json
{
"name": "client",
"version": "1.1.0",
"private": true,
"dependencies": {
"#babel/plugin-proposal-class-properties": "^7.4.0",
"#babel/plugin-transform-runtime": "^7.2.0",
"autosuggest-highlight": "^3.1.1",
"axios": "^0.18.0",
"babel-loader": "^8.0.5",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"body-parser": "^1.18.3",
"css-loader": "^2.1.0",
"d3": "^5.5.0",
"email-validator": "^2.0.4",
"file-loader": "^3.0.1",
"history": "^4.7.2",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"js-file-download": "^0.4.4",
"path": "^0.12.7",
"react": "^16.4.1",
"react-autosuggest": "^9.4.0",
"react-cookie": "^3.0.4",
"react-dnd": "^5.0.0",
"react-dnd-html5-backend": "^5.0.1",
"react-dom": "^16.4.1",
"react-dropdown": "^1.6.2",
"react-phone-number-input": "^2.2.15",
"react-router-dom": "^4.3.1",
"react-scripts": "^3.0.0",
"reactstrap": "^6.3.1",
"save-svg-as-png": "^1.4.7",
"style-loader": "^0.23.1",
"text-loader": "0.0.1",
"topojson-client": "^3.0.0",
"webpack": "^4.29.5",
"webpack-cli": "^3.2.3"
},
"babel": {
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-transform-runtime",
"#babel/plugin-proposal-class-properties"
]
},
"scripts": {
"start": "npm run client",
"client": "webpack-dev-server --config ./webpack.config.js --mode development --host 0.0.0.0",
"build": "webpack --mode production",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
],
"devDependencies": {
"webpack-dev-server": "^3.2.1"
}
}
webpack.config.js
const HtmlWebPackPlugin = require("html-webpack-plugin");
const webpack = require("webpack");
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.(png|jpg)$/,
use: {
loader: 'file-loader',
options: {
name: '[name].[ext]'
}
}
},
{
// Transform our own .css files with PostCSS and CSS-modules
test: /\.css$/,
exclude: /node_modules/,
use: ['style-loader', 'css-loader'],
}, {
// Do not transform vendor's CSS with CSS-modules
// The point is that they remain in global scope.
// Since we require these CSS files in our JS or CSS files,
// they will be a part of our compilation either way.
// So, no need for ExtractTextPlugin here.
test: /\.css$/,
include: /node_modules/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.html$/,
use: ["html-loader"]
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./public/index.html",
filename: "./index.html"
}),
new webpack.DefinePlugin({
'process.env': {
SERVER_URL: JSON.stringify(process.env.SERVER_URL)
},
})
],
externals: ["fs"],
"output": {
filename: '[name].[hash].js'
}
};
Docker
I have in my application the server and client part, for the need, I remove the server part, so we have the Dockerfile for client in services/client/ and the docker-compose file in main project.
Dockerfile - client
# base image
FROM node:11.6.0-alpine
# set working directory
WORKDIR /usr/src/app/client
# add `/usr/src/app/node_modules/.bin` to $PATH
ENV PATH /usr/src/client/app/node_modules/.bin:$PATH
# install and cache app dependencies
COPY package.json /usr/src/app/client/package.json
RUN npm install --silent && \
npm install --silent webpack-dev-server
# start app
CMD ["npm", "start"]
docker-compose.yml - main project
version: '3.7'
services:
client:
container_name: client
build:
context: ./services/client
dockerfile: Dockerfile
volumes:
- ./services/client:/usr/src/app/client
- /usr/src/app/client/node_modules
ports:
- 8080:8080
environment:
- SERVER_URL=http://localhost:5001
depends_on:
- server
nginx:
container_name: nginx
build:
context: ./services/nginx
dockerfile: Dockerfile
restart: unless-stopped
ports:
- "80:80"
depends_on:
- client
I doesn't have found so many things, first I have think that I have forgot something, like a module but It doesn't seems to be that. I need help.
Update
Actually I'm trying to test in local but I'm facing an issue, perhaps it can help.
Error when start in local (npm start)
internal/modules/cjs/loader.js:596
throw err;
^
Error: Cannot find module 'webpack-cli/bin/config-yargs'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:594:15)
at Function.Module._load (internal/modules/cjs/loader.js:520:25)
at Module.require (internal/modules/cjs/loader.js:650:17)
at require (internal/modules/cjs/helpers.js:20:18)
at Object.<anonymous> ($path-to-project/services/client/node_modules/webpack-dev-server/bin/webpack-dev-server.js:77:1)
at Module._compile (internal/modules/cjs/loader.js:702:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
at Module.load (internal/modules/cjs/loader.js:612:32)
at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
at Function.Module._load (internal/modules/cjs/loader.js:543:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! client#1.1.0 client: `webpack-dev-server --config ./webpack.config.js --mode development --host 0.0.0.0`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the client#1.1.0 client 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! /Users/user/.npm/_logs/2019-04-24T14_05_19_879Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! client#1.1.0 start: `npm run client`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the client#1.1.0 start 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! /Users/user/.npm/_logs/2019-04-24T14_05_19_917Z-debug.log
Update 2
I success to start the application in local and seems to work. I have delete the node_modules/ folder and package-lock.json and I install first webpack and after all package.json.
Even if it work in local, on docker, it don't work.
Your volumes: declaration is causing this.
You make things work again if you get into this situation by running:
docker-compose stop client
docker-compose rm client
docker-compose up --build
...but note that this is exactly the set of commands you'd need to run if you didn't have the problematic volumes: declaration.
Your docker-compose.yml file tells Docker:
volumes:
# This directory contains data that needs to be injected from
# and/or persisted to the host. Hide anything that's in the
# image and use this host directory instead.
- ./services/client:/usr/src/app/client
# This directory also contains data that needs to be persisted
# across container runs. Hide anything that's in the volume or
# the previous bind mount and use data in this volume instead.
# ONLY THE FIRST TIME this container gets run, copy data from
# the image into this volume.
- /usr/src/app/client/node_modules
You should be able to create a routine Dockerfile and docker-compose.yml file to illustrate this. npm init a trivial program and run it. If you run, say, docker-compose run client sh, you will be able to see that the node_modules directory matches what's in the current build environment. If you then yarn add anything, though, even if you rebuild the image, the node_modules volume will not get updated: you've told Docker it contains persistent data, and it will only get populated if it's empty.
(The reverse corollary to this is that, if you do use docker-compose run to get a shell like this and hand-edit something in your node_modules directory, because you've asked for that directory to be persisted separately from the image, it will outlive the temporary container that this launches.)
The workflow that's generally worked for me is to use Node directly on the host for active development (and live reloading and good IDE support and ...), and to use Docker (building an image, not injecting code via volumes) for production deployments.
I started working a lot with vue and started to use it in all the projects in the company where I work. And with that, I ended up creating some components, in general autocomplete, I know that there are many, I have already used some, but none have supplied all my needs. However, whenever I go to work on a new project and use the same component, either I recreates it, or I copy and paste it.
So I came to doubt How to create my component, upload to npmjs for whenever I use it, just give a npm install -save ..., and also be able to contribute a bit with the community.
update
With the release of vue-loader 15.x this answer will no longer work. Please use this instead https://medium.freecodecamp.org/how-to-create-a-vue-js-app-using-single-file-components-without-the-cli-7e73e5b8244f
Here is one way you can create/publish a Vuejs library/component from scratch.
As I am going to write down every step and command, make sure to follow the entire guide and you will be able to create and publish your own Vuejs component on NPM.
After you publish it, like most libraries you can install it using ex:
npm install --save your-component
And then import the component inside your app using
import something from 'your-component'
To start creating our first component, first create a folder called vuejs-hello-app (or any other name) and inside it, run:
npm init
Just hit enter until the interactive question ends and then npm will generate a file named package.json in that folder containing the following code.
(Note: I changed the description and version from 1.0.0 to 0.1.0 here is the result.)
{
"name": "vuejs-hello-app",
"version": "0.1.0",
"description": "vuejs library demo",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
After this, we'll need to install the dependencies for our library.
These dependencies are divided into two types: dependency and devDependency
dependency:
is the external library or libraries that our own component runs on. When someone installs your component, npm will make sure this dependency exists or gets installed first. Since we are creating a component for vue, we need to make sure vue is required. So, install it using:
npm install --save vue
devDependency:
is a bunch of libraries that we need only for development purposes. These libraries will help us build and/or transpile.
We install dev dependencies using the method above by adding the the suffix -dev to --save
Now, let us install the minimum dev dependencies we need for our component:
npm install --save-dev babel-core
npm install --save-dev babel-loader
npm install --save-dev babel-preset-env
npm install --save-dev cross-env
npm install --save-dev css-loader
npm install --save-dev file-loader
npm install --save-dev node-sass
npm install --save-dev sass-loader
npm install --save-dev vue-loader
npm install --save-dev vue-template-compiler
npm install --save-dev webpack
npm install --save-dev webpack-dev-server
At this point the libraries will be installed and the package.json will be updated to look like following.
{
"name": "vuejs-hello-app",
"version": "0.1.0",
"description": "vuejs library demo",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack -p"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"cross-env": "^5.1.1",
"css-loader": "^0.28.7",
"file-loader": "^1.1.5",
"node-sass": "^4.7.2",
"sass-loader": "^6.0.6",
"vue-loader": "^13.5.0",
"vue-template-compiler": "^2.5.9",
"webpack": "^3.10.0",
"webpack-dev-server": "^2.9.7"
},
"dependencies": {
"vue": "^2.5.9"
}
}
(note: I have added "build": "webpack -p" to build our lib with webpack)
Now, since our code needs to be built and transpiled, we need a folder to store the build version. Go ahead and create a folder inside our root folder and call it: dist and in the same place a configuration file for webpack and name it webpack.config.js
All of the files we have so far created are for configuring and stuff. For the actual app that people are going to use, we need to create at least two files inside our src/ directory.
A main.js and VuejsHelloApp.vue put them as:
./src/main.js and ./src/components/VuejsHelloApp.vue
I have mine structured like this:
dist
node_modules
src
main.js
components
VuejsHelloApp.vue
.babelrc
.eslintignore
.gitignore
.npmignore
.travis.yml
CONTRIBUTING
LICENSE
package.json
README.md
webpack.config.js
I will just go through the files listed and describe what each file does in-case anyone is curious:
/dist is where a build (transpiled), minified, non-ES6 version of your code will be stores
node_modules I think we know this already, let's ignore it
src/ this is root dir of your library.
.babelrc is where your babel options are kept, so add this to disable presets on modules
{
"presets": [
[
"env",
{
"modules": false
}
]
]
}
.eslintignore This is where you tell ESLINT to ignore linting so put this inside:
build/*.js
.gitignore
add files you want to ignore (from git)
.npmignore same as .gitignore for NPM
.travis.yml if you need CI check examples from travis and configure it
CONTRIBUTING not required
LICENSE not required
package.json ignore for now
README.md not required
webpack.config.js This is the important file that let's you create a build, browser compatible version of your code.
So, according to our app, here is a minimal example of what it should look like:
var path = require('path')
var webpack = require('webpack')
module.exports = {
entry: './src/main.js',
module: {
rules: [
// use babel-loader for js files
{ test: /\.js$/, use: 'babel-loader' },
// use vue-loader for .vue files
{ test: /\.vue$/, use: 'vue-loader' }
]
},
// default for pretty much every project
context: __dirname,
// specify your entry/main file
output: {
// specify your output directory...
path: path.resolve(__dirname, './dist'),
// and filename
filename: 'vuejs-hello-app.js'
}
}
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
])
}
Note that the important directives here are entry and output. You can check webpack docs to learn more if you want to fully customize your app.
But basically, we're telling webpack to get the ./src/main.js (our app) and output it as ./dist/vuejs-hello-app.js
Now, we are almost finished setting up everything except the actual app.
Go to /src/components/VuejsHelloApp.vue and dump this simple app, which will move a button right or left when you hover on it
<template>
<div>
<button #mouseover='move($event)'> I'm alive </button>
</div>
</template>
<script>
export default {
data () {
return {}
},
methods: {
move (event) {
let pos = event.target.style.float;
if(pos === 'left'){
event.target.style.float = 'right'
}else{
event.target.style.float = 'left'
}
}
}
}
</script>
<style scoped>
</style>
And not but not least, got to ./src/main.js and export your app like:
import VuejsHelloApp from './components/VuejsHelloApp.vue'
export default VuejsHelloApp
Now go to your package.json file replace the "main: "index.js", with "main": "src/main.js",
After this, simply run these commands to build and publish your app:
npm run build
git add .
git commit -m "initial commit"
git push -u origin master
npm login
npm publish
Importing and using the library.
If everything went smoothly, then simply install your app like this:
npm install --save vuejs-hello-app
And use it in vue like this:
<template>
<div>
<VuejsHelloApp> </VuejsHelloApp>
</div>
</template>
<script>
import VuejsHelloApp from 'vuejs-hello-app'
export default {
name: 'HelloWorld',
components: { VuejsHelloApp }
}
</script>
I made this app https://github.com/samayo/vuejs-hello-app while writing the answer, it might help to better understand the code
I'm new to react js and I'm trying to set up the environment for it and I followed the steps mentioned in https://www.tutorialspoint.com/reactjs/reactjs_environment_setup.htm.
But after doing all the things mentioned there I'm getting this error:
'webpack-dev-server' is not recognized as an internal or external command, operable program or batch file
If you want to develop an application using babel, webpack, etc. You need to follow following steps. No doubt there are much better tutorial available over the internet but it will give you some idea.
1.Webpack:
In browsers you can not require or import modules as you usually do while writing node.js code. With the help of a module bundler, maybe Webpack, you can write code that uses require/import in the same way that you would use it in node environment. I am assuming you will use webpack considering its popularity.
2. Install dependencies (es6)
These are minimal dependencies you need in your project (package.json) to get it working. You can directly copy paste the following text into a new file named "package.json". run the following set of commands in you EMPTY project directory:
install the node package manager
npm init [follow the command prompt to fill in meta data of your project like name, author,etc.]
install global packages
npm install -g babel babel-cli
[this will install transpiler(babel) into your global environment]
install module bundler
npm install webpack webpack-dev-server --save
install babel plugins
npm install babel-core babel-loader babel-preset-react babel-preset-es2015
After this command set, your package.json will start looking like as following:
{
"name": "reactjs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "No Command Written Yet"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"react": "^15.6.1",
"react-dom": "^15.6.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"
}
}
3.Write your webpack-config.js file
A sample webpack config file should like this. Don't ask me about each bit of it but rather have a look on webpack tutorial because I can not explain everything here. Just remember the fact that
Webpack is a module bundler that bundles javascript and other assets for the browser.
var config = {
entry: './main.js',
output: {
path:'/',
filename: 'index.js',
},
devServer: {
inline: true,
port: 8080
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
module.exports = config;
4.Set up entry point for your application
src->index.js
index.js
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<App />
, document.querySelector('.init')
);
5.Setup index.html in your project root
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Welcome to ReactJs</title>
</head>
<body>
<div class="init"></div>
</body>
<script src="./public/bundle.js"></script>
</html>
6.Running
A slight change is needed in your package.json
replace:
"scripts": {
"test": "No Command Written Yet"
},
with
"scripts": {
"dev": "webpack-dev-server --hot"
},
[this will change the script you will run to execute the app bundled by webpack]
Now, whenever you want to run the project, just be in the project root directory and call:
npm run dev
DONE, Have Fun!
Run:
npm install webpack-dev-server --save-dev
And try again. You got the error because webpack-dev-server couldn't be found in your devDependencies inside of your package.json file
This is happening because you don't have webpack-dev-server installed as a global package, that's why you can execute directly.
The recommended way is installing it locally, in this way you'll avoid this problem.
Here you can find the steps to make it run.
Good luck
I've got a problem to load rxjs into a simple webpack setup (without angular). I'm running:
./node_modules/.bin/webpack --config webpack.config.js --watch
to start webpack. The only file with the app, src/app.ts, starts with:
import { Observable } from 'rxjs';
and this line is highlighted in VSCode and in webpack console with this error:
Cannot find module 'rxjs'.
But the overall output works fine. Just this console error.
tsconfig.json:
{
"compilerOptions": {
"target": "es2015"
},
"files": [
"src/app.ts"
]
}
webpack.config.js:
module.exports = {
entry: "./src/app.ts",
output: {
filename: "dist/bundle.js"
},
resolve: {
// Add '.ts' and '.tsx' as a resolvable extension.
extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
},
module: {
loaders: [
// all files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'
{ test: /\.ts?$/, loader: "ts-loader" }
]
}
}
package.json (everything installed properly):
{
"scripts": {
"start": "./node_modules/.bin/webpack --config webpack.config.js --watch"
},
"devDependencies": {
"ts-loader": "^2.1.0",
"typescript": "^2.3.4",
"webpack": "^2.6.1",
"webpack-dev-server": "^2.4.5"
},
"dependencies": {
"bootstrap": "^3.3.7",
"rxjs": "^5.4.0"
}
}
I can't find the reason for why can't ts/webpack resolve where is rxjs
You should change default module resolution strategy from Classic to Node. In order to do this, change your tsconfig.json file:
{
...
"compilerOptions": {
....
"moduleResolution": "node"
}
}
See documentation on Module Resolution
to ionic
simple use this command in order to delete the plugin
npm uninstall --save rxjs
npm uninstall --save rxjs-compat
and then run this to reinstall
npm install --save rxjs
npm install --save rxjs-compat
I had this issue when I tried building with nestjs from scratch,
this should solve your problem
npm install rxjs
and if that doesn’t, try this:
delete node_modules and package-lock.json
rm -rf node_modules rm -f package-lock.json
clean npm cache
npm cache clean --force
try reinstalling
npm install
You must add node_modules to your webpack resolve.modules config:
resolve: {
modules: [
"node_modules",
path.resolve(__dirname, "app")
],
extensions: [".js", ".json", ".jsx", ".css"],
}
more info on https://webpack.js.org/configuration/resolve/
In js file, i used import to instead of require
import co from 'co';
And tried to run it directly by nodejs since it said import is 'shipping features' and support without any runtime flag (https://nodejs.org/en/docs/es6/), but i got an error
import co from 'co';
^^^^^^
SyntaxError: Unexpected token import
Then i tried to use babel
npm install -g babel-core
npm install -g babel-cli
npm install babel-core //install to babel locally, is it necessary?
and run by
babel-node js.js
still got same error, unexpected token import?
How could I get rid of it?
From the babel 6 Release notes:
Since Babel is focusing on being a platform for JavaScript tooling and not an ES2015 transpiler, we’ve decided to make all of the plugins opt-in. This means when you install Babel it will no longer transpile your ES2015 code by default.
In my setup I installed the es2015 preset
npm install --save-dev babel-preset-es2015
or with yarn
yarn add babel-preset-es2015 --dev
and enabled the preset in my .babelrc
{
"presets": ["es2015"]
}
Until modules are implemented you can use the Babel "transpiler" to run your code:
npm install --save babel-cli babel-preset-node6
and then
./node_modules/babel-cli/bin/babel-node.js --presets node6 ./your_script.js
If you dont want to type --presets node6 you can save it .babelrc file by:
{
"presets": [
"node6"
]
}
See https://www.npmjs.com/package/babel-preset-node6 and https://babeljs.io/docs/usage/cli/
Install packages: babel-core, babel-polyfill, babel-preset-es2015
Create .babelrc with contents: { "presets": ["es2015"] }
Do not put import statement in your main entry file, use another file eg: app.js and your main entry file should required babel-core/register and babel-polyfill to make babel works separately at the first place before anything else. Then you can require app.js where import statement.
Example:
index.js
require('babel-core/register');
require('babel-polyfill');
require('./app');
app.js
import co from 'co';
It should works with node index.js.
babel-preset-es2015 is now deprecated and you'll get a warning if you try to use Laurence's solution.
To get this working with Babel 6.24.1+, use babel-preset-env instead:
npm install babel-preset-env --save-dev
Then add env to your presets in your .babelrc:
{
"presets": ["env"]
}
See the Babel docs for more info.
if you use the preset for react-native it accepts the import
npm i babel-preset-react-native --save-dev
and put it inside your .babelrc file
{
"presets": ["react-native"]
}
in your project root directory
https://www.npmjs.com/package/babel-preset-react-native
It may be that you're running uncompiled files. Let's start clean!
In your work directory create:
Two folders. One for precompiled es2015 code. The other for babel's
output. We'll name them "src" and "lib" respectively.
A package.json file with the following object:
{
"scripts": {
"transpile-es2015": "babel src -d lib"
},
"devDependencies": {
"babel-cli": "^6.18.0",
"babel-preset-latest": "^6.16.0"
}
}
A file named ".babelrc" with the following instructions:
{"presets": ["latest"]}
Lastly, write test code in your src/index.js file. In your case:
import co from 'co'.
Through your console:
Install your packages:
npm install
Transpile your source directory to your output directory with the -d (aka --out-dir) flag as, already, specified in our package.json:
npm run transpile-es2015
Run your code from the output directory!
node lib/index.js
Current method is to use:
npm install --save-dev babel-cli babel-preset-env
And then in in .babelrc
{
"presets": ["env"]
}
this install Babel support for latest version of js (es2015 and beyond)
Check out babeljs
Do not forget to add babel-node to your scripts inside package.json use when running your js file as follows.
"scripts": {
"test": "mocha",
//Add this line to your scripts
"populate": "node_modules/babel-cli/bin/babel-node.js"
},
Now you can npm populate yourfile.js inside terminal.
If you are running windows and running error internal or external command not recognized, use node infront of the script as follow
node node_modules/babel-cli/bin/babel-node.js
Then npm run populate
You have to use babel-preset-env and nodemon for hot-reload.
Then create .babelrc file with below content:
{
"presets": ["env"]
}
Finally, create script in package.json:
"scripts": {
"babel-node": "babel-node --presets=env",
"start": "nodemon --exec npm run babel-node -- ./index.js",
"build": "babel src -d dist"
}
Or just use this boilerplate:
Boilerplate: node-es6
install --> "npm i --save-dev babel-cli babel-preset-es2015
babel-preset-stage-0"
next in package.json file add in scripts "start": "babel-node server.js"
{
"name": "node",
"version": "1.0.0",
"description": "",
"main": "server.js",
"dependencies": {
"body-parser": "^1.18.2",
"express": "^4.16.2",
"lodash": "^4.17.4",
"mongoose": "^5.0.1"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-0": "^6.24.1"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "babel-node server.js"
},
"keywords": [],
"author": "",
"license": "ISC"
}
and create file for babel , in root
".babelrc"
{
"presets":[
"es2015",
"stage-0"
]
}
and run npm start in terminal
Involve following steps to resolve the issue:
1) Install the CLI and env preset
$ npm install --save-dev babel-cli babel-preset-env
2) Create a .babelrc file
{
"presets": ["env"]
}
3) configure npm start in package.json
"scripts": {
"start": "babel-node ./server/app.js",
"test": "echo \"Error: no test specified\" && exit 1"
}
4) then start app
$ npm start
I have done the following to overcome the problem (ex.js script)
problem
$ cat ex.js
import { Stack } from 'es-collections';
console.log("Successfully Imported");
$ node ex.js
/Users/nsaboo/ex.js:1
(function (exports, require, module, __filename, __dirname) { import { Stack } from 'es-collections';
^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:152:10)
at Module._compile (module.js:624:28)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
at Function.Module._load (module.js:505:3)
at Function.Module.runMain (module.js:701:10)
at startup (bootstrap_node.js:194:16)
at bootstrap_node.js:618:3
solution
# npm package installation
npm install --save-dev babel-preset-env babel-cli es-collections
# .babelrc setup
$ cat .babelrc
{
"presets": [
["env", {
"targets": {
"node": "current"
}
}]
]
}
# execution with node
$ npx babel ex.js --out-file ex-new.js
$ node ex-new.js
Successfully Imported
# or execution with babel-node
$ babel-node ex.js
Successfully Imported
#jovi all you need to do is add .babelrc file like this:
{
"plugins": [
"transform-strict-mode",
"transform-es2015-modules-commonjs",
"transform-es2015-spread",
"transform-es2015-destructuring",
"transform-es2015-parameters"
]
}
and install these plugins as devdependences with npm.
then try babel-node ***.js again. hope this can help you.
In your app, you must declare your require() modules, not using the 'import' keyword:
const app = require("example_dependency");
Then, create a .babelrc file:
{
"presets": [
["es2015", { "modules": false }]
]
}
Then, in your gulpfile, be sure to declare your require() modules:
var gulp = require("gulp");