// 堆代码 duidaima.com import React from 'react'; import _ from 'lodash';然而,如果我们把这行代码直接放到一个 <script type="module"> 标签里,并在浏览器中打开,迎接我们的将是一个冰冷的错误:
Uncaught TypeError: Failed to resolve module specifier "react". Relative references must start with "./", "../", or "/".这个错误困扰了我们很多年。浏览器不认识像 react 或 lodash 这样的“裸模块”(Bare Module Specifier)。它只理解相对路径 (./utils.js) 或绝对路径 (/src/main.js)。
<!DOCTYPE html> <html> <head> <title>Hello Import Maps!</title> <!-- 1. 定义 Import Map --> <script type="importmap"> { "imports": { "react": "https://esm.sh/react@18.2.0", "lodash": "https://esm.sh/lodash-es@4.17.21", "app/": "./src/app/" } } </script> </head> <body> <div id="root"></div> <!-- 2. 像在 Node.js 环境中一样,直接使用裸模块导入 --> <script type="module"> import React from 'react'; import { camelCase } from 'lodash'; import { sayHello } from 'app/utils.js'; // 也能映射路径前缀 console.log(React.version); // "18.2.0" console.log(camelCase('hello world')); // "helloWorld" sayHello(); // "Hello from utils!" </script> </body> </html>一切都如此自然,无需任何构建步骤,没有 Webpack,没有 Rollup,甚至不需要 node_modules 文件夹(对于纯浏览器依赖)。我们只需要一个文本编辑器和一个现代浏览器。
3.资源预处理