一、前言
OpenLayers的官网给我们提供了相当多的例子,打开一个例子你就能直接看到运行效果还有一些说明,接着就是下面的代码:main.js
、index.html
、package.json
但如果一个纯纯纯小白比如我,点开来之后可能会有些懵:
还没学到JS模块化编程,就可能看不懂这一堆的import:
import 'ol/ol.css';
import Map from 'ol/Map';
import OSM from 'ol/source/OSM';
或者是还没学过node.js的可能会不知道每个例子最下面为啥会有个 `package.json`
看着这些都贴脸上的代码,对只学过简单的HTML+CSS+一点点JavaScript的我来说,属实是无从下手。
二、开始
然后今天看黑马程序员Vue全套视频教程,从vue2.0到vue3.0一套全覆盖,前端必会的框架教程的时候,刚好学到了一点node.js的知识。现学现用,开始试试自己能不能打开ol官网的例子。
环境:Windows11 + Visual Code
2.1 首先安装node.js
2.2 新建项目
- 新建一个空文件夹
- 用vscode打开项目文件夹
- 在vscode的终端里输入:
npm init -y
- 成功后会得到一个
package.json
文件。
2.3 拷贝案例源代码
- 就比如直接用这个例子:Full Screen Control with extended source element
- 复制里面的
index.html
和main.js
到项目的根目录中。
2.4 配置ol和parcel
- 在vscode的终端处输入:
npm install ol -S
npm install parcel -D
- 前者是安装OpenLayers的包
- 后者是安装Parcel的包
- 成功之后可以在
package.json
中看到它们:
- 然后修改一下
package.json
中 “scripts”: {}里的内容
将
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
改成
"scripts": {
"start": "parcel index.html",
"build": "parcel build --public-url . index.html"
},
2.5 开始调试
- 可以直接点击package.json里的调试小按钮,选择start
- 铛铛!报错:
报错全文:
PS X:\Repository\newstart\day1> npm run start
Debugger attached.
> day1@1.0.0 start
> parcel index.html
Debugger attached.
Server running at http://localhost:1234
× Build failed.
@parcel/transformer-js: Browser scripts cannot have imports or
exports.
X:\Repository\newstart\day1\main.js:1:1
> 1 | import 'ol/ol.css';
> | ^^^^^^^^^^^^^^^^^^^
2 | import Map from 'ol/Map';
3 | import OSM from 'ol/source/OSM';
X:\Repository\newstart\day1\index.html:7:5
6 | <!-- Pointer events polyfill for old browsers, see https:/
> 7 | <script src="https://unpkg.com/elm-pep"></script>
> | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The environment was originally created here
8 | <!-- The line below is only needed for old environments li
9 | <script src="https://cdn.polyfill.io/v3/polyfill.min.js?fe
ℹ Add the type="module" attribute to the <script> tag.
ℹ Learn more:
https://parceljs.org/languages/javascript/#classic-scripts
- 按照提示,我们在index.html的
<script>
中添加type="module"
- 再来一遍,成功!控制台显示:
PS X:\Repository\newstart\day1> npm run start
Debugger attached.
> day1@1.0.0 start> parcel index.html
Debugger attached.
Server running at http://localhost:1234
√ Built in 1.90s
- 打开 http://localhost:1234 得到:
三、最后
因为自己也是刚开始学,所以很多东西都不是很了解,但是能成功运行出来就已经很满足了。等后续node.js学得差不多了再回来修改这篇文章中的错误吧(虽然不知道有没有错)。