我正在摸索 ES6 的过程,遇到了模块(很好!),在学习过程中,我试图看看是否可以在浏览器中使用它们withoutWebPack(我还没学过)。
-
所以,我的 JS 目录中有以下文件/文件夹结构
js
- lib (for complied es6 via Babel)
- mods (compiled modules)
- module.js (compiled via Babel)
- app.js (imports modules, attached to index.html)
- src (for "raw" es6)
- mods (es6 modules)
- module.js (es6 module)
- app.js (imports modules)
-
在 js/src/mods/module.js 中,我有以下代码......
export const topTime = 1.5;
export const subTime = 0.75;
-
由 js/src/app.js 导入...
import { topTime, subTime } from './mods/modules';
console.log(topTime);
console.log(subTime);
-
然后我将所有 es6 文件编译为 es5(将文件放置在 lib 目录中)。
npm run babel
-
Now I can在我的编辑器(vscode/output 选项卡)中运行主文件(js/lib/app.js)
[Running] node "/home/me/www/es6.local/js/lib/app.js"
1.5
0.75
...但我认为这只是因为它在节点中运行。
-
当我在浏览器(FF)中调用我的index.html文件(带有js/lib/app.js)时,它会中断,因为我收到以下错误...
ReferenceError: require is not defined
-
所以我看到 babel 编译了这个......
import { topTime, subTime } from './mods/modules';
进入这个...
var _modules = require('./mods/modules');
...但我认为这是有效的 es5? ...不?那么在 webpack 之前这是如何完成的呢?请指教。
这是我的package.json
(如果有帮助的话)...
{
"name": "es6.local",
"version": "0.0.1",
"description": "JavaScript ES6 Testing Sandbox",
"main": "index.html",
"scripts": {
"babel": "babel js/src --out-dir js/lib --source-maps"
},
"author": "Student",
"license": "ISC",
"devDependencies": {
"eslint": "^4.16.0",
"eslint-plugin-import": "^2.8.0",
"eslint-plugin-jsx-a11y": "^6.0.3",
"eslint-plugin-react": "^7.6.0",
"eslint-config-airbnb": "^16.1.0",
"babel-cli": "^6.26.0",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.6.1"
},
"babel": {
"presets": [
[
"env",
{
"targets": {
"browsers": [
"last 2 versions",
"safari >= 7"
]
}
}
]
]
}
}