My project didn’t have package.json
earlier, but now I have to add npm packages to the site.
I typed in project root directory npm init
, after npm i moment
and package has been installed, but index.js file doesn’t see it, so this code import moment from 'moment';
returns me an error:
dex.html:1 Uncaught TypeError: Failed to resolve module specifier "moment". Relative references must start with either "/", "./", or "../".
which probably means that it tries to receive export from the file.
So I decided to manually provide the whole path to the file as ../../node_modules/moment/moment.js
, but moment.js doesn’t have export at all.
Anyway I would needed to add Node.js to the project, as I’m going to connect site via express, so it has to be added correctly
Update based on @Nonik’s comment: I tried to use const moment = require('moment');
but it returns me:
dex.js:11 Uncaught ReferenceError: require is not defined
My main file is index.html
Here is the repo
2
Answers
You need to use some form of bundler, like Webpack. Node.js may load files from the filesystem, but a web browser has no concept of a "module" or "exports" (pre-ESM, that is). A bundler is a separate build step which integrates Webpack’s code with your own code that is possible to use on the web.
You can also use a
script
tag or ESM to import directly from a CDN like unpkg.