从浏览器的es6模块中无法识别的node_modules导入 [英] Import from node_modules not recognized in es6 modules in browser

查看:6122
本文介绍了从浏览器的es6模块中无法识别的node_modules导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的Web应用程序中使用lodash.我已经在本地项目中使用npm安装了lodash.

I'm trying to use lodash in my web application. I have installed lodash using npm in my local project.

我打算在代码中使用ES6模块.

I plan on using the ES6 modules in my code.

这是我的main.js文件:

Here is my main.js file:

import * as _ from "lodash";

_.each([1, 2, 3, 4], (i) => {
    console.log('index each ' + i);
});

我将它包含在index.html中为:

And I have included it in index.html as:

<script src="js/main.js", type="module"></script>

但是我在浏览器控制台中遇到以下错误.

But I get the following error in the browser console.

未捕获的TypeError:无法解析模块说明符"lodash". 相对引用必须以"/"、./"或"../"开头.

Uncaught TypeError: Failed to resolve module specifier "lodash". Relative references must start with either "/", "./", or "../".

注意:我不希望使用任何捆绑工具.

Note: I do not wish to use any bundling tool.

推荐答案

如果您不想使用任何捆绑工具,则需要提供相对于JavaScript文件的node_modules中lodash文件夹的路径.您有导入语句.

If you don't wish to use any bundling tools, you will need to provide a path to the lodash folder within node_modules, relative to the JavaScript file that you have the import statement in.

如果您不想使用捆绑程序,那么从特定文件(您需要的功能)中导入也是值得的.例如:

If you do not wish to use a bundler, it would also be worthwhile importing from the specific file, the function you need. For example:

import _each from '../node_modules/lodash/each'

这篇关于从浏览器的es6模块中无法识别的node_modules导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆