Search code examples
javascriptnode.jsnpmimportrequirejs

cannot import or require node modules (using npm)


Versions

I am working on a relatively old Laravel 7 project.

npm -v
8.15.0

node -v
v14.17.1

The Issue

I installed a new package using npm

npm i my_new_package

and am now trying to import the package from my js:

<script type="module" src="/js/filename.js"></script>

filename.js:

import { Roulette } from "my_new_package";

// Uncaught TypeError: Failed to resolve module specifier "@theblindhawk/roulette".
// Relative references must start with either "/", "./", or "../".
const Roulette = require("my_new_package");

// Uncaught ReferenceError: require is not defined

I tried a bunch of stuff from other SO questions, but none of it seemed to work.
There were no issues when I tried creating a file in the same repository and calling it.

import { Roulette } from "./different_file.js";

I am guessing this has to do with CommonJS/ES6, but my knowledge about these is quite lacking.


Solution

  • I messed up at the very basics...
    Probably cuz I was recently working on a Laravel project with an different file creation method.

    I forgot I had to put my js files in the resouces folder, then call them from the webpack.mix.js.
    The webpack file:

    mix.js('resources/js/filename.js', 'public/js')
    

    Then run npm run watch and it will create the files inside the public folder for you.