In my project I use webpack and npm. I installed moment.js : npm install moment. Then I want to import it in my app.js file: import moment from "moment".
But it doesn't work. I get: Can't resolve moment in ...
I try let moment = require('moment');but I get the same error.
But I can require it in my webpack.config.js file without errors.
My app.js file is located on /myapp/frontend/app.js
My webpack.config.js file on:/myapp/webpack.config.js
So, please explain why I can't require moment in my app.js and how can I do this?
My config file:
const webpack = require("webpack");
const NODE_ENV = process.env.NODE_ENV || "development"
const path = require('path');
//example of successfull importing
let moment = require('moment');
console.log(moment(new Date()));
module.exports = {
context: __dirname + "/frontend",
entry: {
app:"./app"
},
output: {
path: path.resolve(__dirname,"./public/js"),
publicPath:"/public/js/",//public path in internet
filename: "build.js"
},
watch: NODE_ENV == "development",
watchOptions:{
aggregateTimeout:100//default = 300
},
devtool: NODE_ENV == "development"?"cheap-inline-module-source-map":"cheap-source-map",
//cheap-inline-module-source-map - to see sources in build.js
//eval - fastest
resolve:{
modules: ['node-modules'],
extensions:['.js']
},
module:{
loaders:[{
test: /\.js$/,
loader:"babel-loader?presets[]=es2015",
exclude: /node_modules/
}]
}
};
if(NODE_ENV == "production"){
module.exports.plugins.push(
new webpack.optimize.UglifyJsPlugin({
compress:{
warnings:false,
unsafe:true,
drop_console:true
}
})
);
}
It is my tree structure without node_modules folder:
SOLVING OF PROBLEM: problem was in my configuration:
resolve:{
modules: ['node-modules'],
extensions:['.js']
},
There is node-modules is wrong, must be node_modules. Simple typo..
For my issue, I have change import {moment} from 'moment' to import * as moment from 'moment'; and it's working now!
Without knowing a bit more about your file structure it's difficult to be certain as to why, but the issue is probably that your webpack config is not finding the moment module in your node_modules.
As a test, ran the following:
//webpack.js
const path = require('path');
module.exports = {
entry: path.join(__dirname, '..', 'public', 'js', 'index.js'),
output: {
filename: 'app.js',
path: path.resolve(__dirname, '..', 'public', 'dist'),
},
};
and then with moment and jquery installed via npm install --save jquery moment, I made a index.js file:
import $ from jquery;
import moment from moment;
const m = moment();
No build errors and no runtime errors when included on the HTML page. Try starting simply first and then build up from there on your webpack config. Also, I'm not sure if webpack does anything with package.json but I noticed you didn't signal the --save option. It's a good habit to get into.
In my case, issue was solved when I put window.moment = require('moment');
Related
My website doesn't load because the request for bundle.js instead returns the index.html file.
This project is from a few years ago and at the time it worked fine, but I'm trying to get it up and running again and I'm not sure why this is happening now. If anyone can help, I'd really appreciate it!
File structure:
- src
- app
- db
- public
- assets (folder)
- styles (folder)
- index.html
- server
- auth (folder)
- routers (folder)
- server.js
- webpack.config.js
webpack.config.js:
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: path.resolve(__dirname, 'src/app', 'client.jsx'),
output: {
path: path.resolve(__dirname, 'src/public/build'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.jsx?$/,
include: path.resolve(__dirname, 'src/app'),
loader: 'babel-loader'
}
]
},
devtool: 'source-map'
};
From index.html:
<body>
<div id="app"></div>
<!-- load the app scripts -->
<script src="/build/bundle.js"></script>
</body>
From server.js:
app.use(express.static(path.resolve(__dirname, '../public')));
app.use('*', function (request, response){
response.sendFile(path.resolve(__dirname, '../public', 'index.html'))
})
From package.json:
"scripts": {
"start": "webpack --watch | nodemon --ignore node_modules ./src/server/server.js --exec babel-node"
},
From .babaelrc:
{
"presets": [
"#babel/preset-env",
"#babel/preset-react",
"airbnb"
],
"plugins": [
["#babel/plugin-proposal-decorators", { "legacy": true }],
["#babel/plugin-proposal-class-properties", { "loose": true }],
"react-html-attrs",
"transform-class-properties",
]
}
[reputation is too low to comment]
Everything looks kosher, so I agree with #eol the first step is to actually transpile and confirm the build is working as intended.
As a semi-related aside, I believe you should move the path resolution in the main request handler to be a constant that is only invoked and resolved once... probably a minimal gain, but as it stands every request has the same path resolved.
const indexFile = path.resolve(__dirname, '../public', 'index.html');
app.use('*', function (request, response) { response.sendFile(indexFile); });
(This isn't relevant for the first handler, as the resolution will only occur once when the static method is invoked.)
Regarding the start script: I don't think you want to be piping the output from the webpack --watch command to nodemon? You probably want to push the webpack command to run in the background and then execute nodemon. I don't even think webpack watch will actually exit so nodemon would never be called?
Try webpack --watch & nodemon ....
I don't see anything that jumps out as to why the build wouldn't be working besides that... does it compile if you just run webpack in your terminal in the root directory?
I am developping a library that needs to work in both node and a react app. I use a webpack 4 project that generates a UMD module, but I have a problem when I try to import it in a simple webpack project.
When I use import lib from 'myLib'; lib is undefined
This is what my lib look like
export const printMsg = function() {
return "This is a message from the lib";
};
With this webpack configuration
const path = require("path");
module.exports = {
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "mylib.js",
library: "mylib",
libraryTarget: "umd",
umdNamedDefine: true,
globalObject: `(typeof self !== 'undefined' ? self : this)`
}
};
for now I'm using a boilerplate project (https://github.com/wbkd/webpack-starter) to test.
I used npm install --save mylib to add it, and my dist code is inside my node_modules folder.
My index.js file look like this :
import "../styles/index.scss";
import lib from "watson-tile-lib";
console.log(lib);
When I run the page I got undefined in my browser console.
Any idea ?
what is your main field in package.json? It should be the builded target like:
main: "dist/mylib.js"
I have added a webpack.config.js for my project. It's like this.
const webpack = require('webpack');
var config = {
entry: './src/index.js',
output: {
path: __dirname,
filename: './public/js/bundle.js'
}
};
module.exports = config;
I tried running project with npm start but bundle.js is not generating any content.
File structure is like this.
/node_modules
/public
/public/index.html
/public/js/bundle.js
/src/index.js
/src/components
/webpack.config.js
Project start in a normal way but bundle.js no content. What would be the issue?
I followed almost all guides I found online and I can not make debugger in IntelliJ stop at breakpoints.
I am developing React app with router. Backend is in Play Framework.
I tried generating source map using. This is from gulpFiles:
var bundler = watchify(browserify('./frontend/app.jsx', { debug: true }).transform(babel, {
presets: ["es2015","react","stage-3"],
plugins: [
"transform-decorators-legacy",
"transform-runtime"
]
}));
Source maps were generated; I was able to debug in Chrome debugger but I am not able in IntelliJ. I only see console output.
I tried generating with webpack:
var webpack = require('webpack');
var path = require('path');
var BUILD_DIR = path.resolve(__dirname, 'public/javascripts');
var APP_DIR = path.resolve(__dirname, 'frontend');
var config = {
entry: APP_DIR + '/app.jsx',
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
module : {
loaders : [
{
test : /\.jsx?/,
include : APP_DIR,
loader : 'babel-loader'
}
]
},
devtool: "source-map"
};
module.exports = config;
Same thing I can not stop at breakpoints in IntelliJ.
I configured JavaScript debug like this:
Name: React Debug
URL: http://localhost:9000/index
Remote URLs of local files (optional) : ./frontend
Still no luck and breakpoints are not working. What am I missing??
I managed to get it working with Webpack.
I was using npm task to run webpack and instead of :
webpack -d --watch
as was suggested everywhere. I used this:
webpack --debug --output-pathinfo --watch
I am trying to publish a package on npm (this one) that I am developing using webpack and babel. My code is written in ES6. I have a file in my sources, index.js, that (for the moment) exports one of my library's core components, it simply goes like this:
import TheGamesDb from './scrapers/thegamesdb';
export { TheGamesDb };
I am using webpack and babel to create a dist index.js that is my package's main file. My webpack.config.js goes like this:
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');
module.exports = {
entry: {
index: ['babel-polyfill', './src/index.js'],
development: ['babel-polyfill', './src/development.js']
},
output: {
path: '.',
filename: '[name].js',
library: 'rom-scraper',
libraryTarget: 'umd',
umdNamedDefine: true
},
devtool: 'source-map',
module: {
loaders: [
{ test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }
]
},
target: 'node',
externals: [nodeExternals()]
};
Now when I load my package in another project and try to import my export TheGamesDb simply like this
import { TheGamesDb } from 'rom-scraper';
I get the error
Uncaught TypeError: Path must be a string. Received undefined
It is to be noted that I am importing my library in electron.
Update: Electron seems to be the main problem here and it is not even my library but a dependency that throws this error (only in Electron)
The problem wasn't any of the things in my question but node-expat not working in electron. I switched to an alternative library and it's all right now.