简体   繁体   English

在浏览器中使用模块(没有 WebPack)

[英]Using Modules in the Browser (without WebPack)

I'm grokking my way through ES6 and I ran into Modules (nice!) and in learning, I am trying to see if I can use them in the browser without WebPack (which I haven't learned yet).我正在探索 ES6,我遇到了模块(很好!),在学习中,我试图看看是否可以在没有WebPack 的浏览器中使用它们(我还没有学习)。

  1. So, I have the following files/folder structure in my JS directory所以,我的 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)
  2. In js/src/mods/module.js, I have the following code....在 js/src/mods/module.js 中,我有以下代码....

     export const topTime = 1.5; export const subTime = 0.75;
  3. Which is imported by js/src/app.js ...这是由 js/src/app.js 导入的...

     import { topTime, subTime } from './mods/modules'; console.log(topTime); console.log(subTime);
  4. I then compiled all es6 files to es5 (which placed the files in the lib dir.)然后我将所有 es6 文件编译为 es5(将文件放在 lib 目录中。)

     npm run babel
  5. Now I can run the main file (js/lib/app.js) inside my editor (vscode/output tab)现在我可以在我的编辑器(vscode/output 选项卡)中运行主文件(js/lib/app.js)

     [Running] node "/home/me/www/es6.local/js/lib/app.js" 1.5 0.75

...but I think that is only because it's running in node. ...但我认为那只是因为它在 node.js 中运行。

  1. It breaks when I call my index.html file (with js/lib/app.js) in the browser (FF) as I get the following error...当我在浏览器 (FF) 中调用我的 index.html 文件(使用 js/lib/app.js)时它会中断,因为我收到以下错误...

     ReferenceError: require is not defined
  2. So I see that babel compiled this...所以我看到 babel 编译了这个......

     import { topTime, subTime } from './mods/modules';

    into this...进入这个...

     var _modules = require('./mods/modules');

...But I thought this was valid es5? ...但我认为这是有效的 es5? ...no? ……没有? So HOW was this done BEFORE webpack?那么在 webpack 之前这是如何完成的呢? Please advise.请指教。


Here is my package.json (in case it helps)...这是我的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"
            ]
          }
        }
      ]
    ]
  }
}

I've been stuck with this for a while and after playing around I found a solution.我已经被这个问题困扰了一段时间,在玩弄之后我找到了一个解决方案。 You don't need any libraries or webpack to do this and I'm not sure this works outside of chrome.你不需要任何库或 webpack 来做到这一点,我不确定这在 chrome 之外是否有效。

  1. You need to run this code on a webserver or else it won't work (in other words, it has to be on localhost, NOT file://)您需要在网络服务器上运行此代码,否则它将无法工作(换句话说,它必须在本地主机上,而不是 file://)
  2. Make a folder called jsmodule创建一个名为jsmodule的文件夹
  3. create a file called index.html with the following code:使用以下代码创建一个名为index.html的文件:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Js module</title>
</head>
<body>
    <h1>JS module test</h1>
    <script type="module" src="script.js"></script>
</body>
</html> 
  1. Create a file in same folder called script.js with the following code:使用以下代码在名为script.js同一文件夹中创建一个文件:
import Person from './Person.js';
import Book from './Book.js';


let person1 = new Person();
let someBook = new Book();
  1. create a file in same folder called Person.js with the following code:使用以下代码在名为Person.js同一文件夹中创建一个文件:
export default class Person{
    constructor(){
        alert("hallo from person");
    }
}
  1. create a file in same folder called Book.js with the following code:使用以下代码在名为Book.js同一文件夹中创建一个文件:
export default class Book{
    constructor(){
        alert("Hallo from book");
    }
}
  1. Run the index.html on you webserver (localhost)在您的网络服务器(本地主机)上运行index.html

It's a pain.这是一种痛苦。

exports and require are part of the CommonJS spec. exportsrequire是 CommonJS 规范的一部分。 If I remember correctly, webpack implements it internally.如果我没记错的话,webpack 在内部实现了它。 You need the same functionality, because it's not part of ES5.您需要相同的功能,因为它不是 ES5 的一部分。

Try RequireJS , or something similar to load your modules.尝试RequireJS或类似的东西来加载你的模块。

In the HTML在 HTML 中

script src="/my-script.js" type="module">

In the script在脚本中

import axios from './axios.js';

The script tag in the HTML needs to have the type of module, else the parser will not understand what import is. HTML 中的脚本标签需要具有模块的类型,否则解析器将无法理解导入是什么。

The import statement needs to have the full path to the JS file you're importing (relative paths should be fine): you cannot do import axios from 'axios' because that's just a string — the browser has no idea if that's even a file or where that file is. import 语句需要包含您要导入的 JS 文件的完整路径(相对路径应该没问题):您不能从 'axios' 导入 axios,因为那只是一个字符串——浏览器不知道这是否是一个文件或者那个文件在哪里。

The browser has no idea what NPM is.浏览器不知道 NPM 是什么。 It's a package manager for Node, it's not connected to JavaScript in general.它是 Node 的包管理器,一般不连接到 JavaScript。 You need the actual file (which you could use NPM to add to your project, then the path will be something like ./node_modules/axios/dist/axios.js您需要实际文件(您可以使用 NPM 添加到您的项目中,然后路径将类似于./node_modules/axios/dist/axios.js

but even using this could create some problem as it some internal dependency over some packages or libraries in node_modules folder但即使使用它也可能会产生一些问题,因为它对 node_modules 文件夹中的某些包或库有一些内部依赖性

I would recommend using webpack or any blunder tool我建议使用 webpack 或任何错误的工具

which auto-magically use NPM modules then bundle everything up into a single output file.它会自动神奇地使用 NPM 模块,然后将所有内容捆绑到一个输出文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM