I am trying to import a simple npm script on the client side which is a function that takes in a single parameter: "name" and just returns Hello name.
After having installed the package via npm install I have made numerous attempts to import the script into my main.js file and nothing has worked:
Steps taken:
use var helloworld = require(‘@xxxxx/hello-world)
Result: Require is not defined
import helloworld from (‘@xxxx/hello-world)
Result: Cannot use import statement outside of a module… Also putting type module into package.json has no effect.
Using browserify
Using Clientside-require
None of the above steps work.
Is it actually possible to just import the simplest of functions as an npm script on clientside?
This is the simple file structure:
2
Answers
The steps in the following article were correct: after following them I was able to import the module correctly via node_modules:
https://marcin.page/posts/free-private-npm-package-using-github/
Browserify just created more problems for me than it solved and just wasted my time.
Browsers have no native support for CommonJS modules. If you want to use a CommonJS module then you must transpile it with a tool like browserify.
Browsers are not Node.js. package.json is not used by browsers.
To use an ECMAScript module in a browser use
<script type="module">
.You also need to import from a URL. Browsers will not search
node_modules
for a module name.See the MDN documentation for more details and examples.
Unless the module depends on Node.js-specific features (such as the
fs
module), browserify should work fine. There isn’t enough information in your question to determine why it isn’t working for you.Ditto.