如何在Vanilla JS文件中正确导入Lodash并解决导入报错
我通过npm install --save lodash安装了lodash库,希望在Vanilla JS文件中用它实现对象深克隆,当前的HTML和JS文件如下:
HTML文件
<!DOCTYPE html> <html lang="en"> <body> <script type="module" src="scripts.js" ></script> </body> </html>
JS文件(scripts.js)
import _ from 'lodash'; let userOne = { name: "Siju", userFunction:function(){ return this.name; } }; // 深克隆部分 let userTwo=_.cloneDeep(userOne); userTwo.name="Johnson"; userTwo.userFunction=function(){ return this.name.length } console.log(userOne.name); console.log(userTwo.name); console.log(userOne.userFunction()); console.log(userTwo.userFunction());
遇到的报错
错误1(使用
import _ from 'lodash';时):Uncaught TypeError: Failed to resolve module specifier "lodash". Relative references must start with either "/", "./", or "../".
错误2(使用
import _ from './node_modules/lodash';时):Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.
简单可行的修复方法
方法1:直接导入lodash的具体JS文件
修改scripts.js中的导入语句,指向node_modules里lodash的编译后JS文件:
// 导入完整的lodash文件 import _ from './node_modules/lodash/dist/lodash.js'; // 或者如果你想用ES模块版本的lodash,可先安装lodash-es再导入 // import _ from './node_modules/lodash-es/lodash.js';
这种方式导入的是明确的JS文件,既符合ES模块的相对引用规则,也不会触发MIME类型错误。
方法2:使用CDN导入(无需本地node_modules)
直接通过CDN地址导入lodash的ES模块版本,无需依赖本地安装的包:
import _ from 'https://cdn.jsdelivr.net/npm/lodash-es@4.17.21/lodash.min.js';
这种方式无需配置本地文件路径,直接打开HTML即可生效。
方法3:使用本地静态文件服务器(可选)
如果不想修改导入路径,可以用简单的本地服务器工具运行项目:
- 安装serve工具:
npm install -g serve - 在项目根目录执行:
serve - 访问控制台给出的本地地址(比如
http://localhost:3000)
本地服务器会正确处理node_modules里文件的MIME类型,此时你可以直接使用import _ from 'lodash';(需配合package.json添加"type": "module",或改用lodash-es包)。
内容的提问来源于stack exchange,提问作者Ren Jitsm

