浏览器内 JavaScript 需要节点样式吗?

发布于 2024-11-28 13:34:28 字数 1539 浏览 2 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

残花月 2024-12-05 13:34:28

我意识到可能有初学者希望组织他们的代码。现在是 2022,如果您正在考虑开发模块化 JS 应用,那么您应该立即开始使用 npmWebpack

以下是一些简单的入门步骤:

  1. 在项目根目录中,运行 npm init -y 来初始化 npm 项目
  2. 下载 Webpack 模块捆绑程序:npm install webpack webpack-cli >
  3. 创建一个index.html文件:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>App</title>
</head>
<body>
    
    <script src="_bundle.js"></script>
</body>
</html>

特别注意_bundle.js文件 - 这将是webpack生成的最终JS文件,你不会直接修改它(继续阅读)。

  1. 创建一个 /app.js,您将在其中导入其他模块:
const printHello = require('./print-hello');

printHello();
  1. 创建一个示例 print-hello.js 模块:
module.exports = function() {
    console.log('Hello World!');
}
  1. 创建一个 < ;project-root>/webpack.config.js 并复制粘贴以下内容:
var path = require('path');

module.exports = {
  entry: './app.js',
  output: {
    path: path.resolve(__dirname),
    filename: '_bundle.js'
  }
};

在上面的代码中,有两点:

  • 入口 app.js 是您编写 JS 的位置代码。它将导入其他模块,如上所示。
  • 输出 _bundle.js 是 webpack 生成的最终包。这就是您的 html 最后将看到的内容。
  1. 打开 package.json,并将 scripts 替换为以下命令:
  "scripts": {
    "start": "webpack --mode production -w"
  },
  1. 最后运行脚本 watch app.js 并生成 _bundle.js 文件,运行:npm start
  2. 享受编码的乐趣!

I realize there may be beginners looking to organize their code. This is 2022, and if you're considering a modular JS app, you should get started with npm and Webpack right now.

Here are a few simple steps to get started:

  1. In your project root, run npm init -y to initialize an npm project
  2. Download the Webpack module bundler: npm install webpack webpack-cli
  3. Create an index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>App</title>
</head>
<body>
    
    <script src="_bundle.js"></script>
</body>
</html>

Pay special attention to _bundle.js file - this will be a final JS file generated by webpack, you will not modify it directly (keep reading).

  1. Create a <project-root>/app.js in which you will import other modules:
const printHello = require('./print-hello');

printHello();
  1. Create a sample print-hello.js module:
module.exports = function() {
    console.log('Hello World!');
}
  1. Create a <project-root>/webpack.config.js and copy-paste the following:
var path = require('path');

module.exports = {
  entry: './app.js',
  output: {
    path: path.resolve(__dirname),
    filename: '_bundle.js'
  }
};

In the code above, there are 2 points:

  • entry app.js is where you will write your JS code. It will import other modules as shown above.
  • output _bundle.js is your final bundle generated by webpack. This is what your html will see at the end.
  1. Open your package.json, and replace scripts with the following command:
  "scripts": {
    "start": "webpack --mode production -w"
  },
  1. And finally run the script watch app.js and generate the _bundle.js file by running: npm start.
  2. Enjoy coding!
梦里南柯 2024-12-05 13:34:28

查看 ender。它做了很多这样的事情。

另外, browserify 也相当不错。我已经使用了 require-kiss1 并且它有效。可能还有其他人。

我不确定 RequireJS。它只是与节点不一样。从其他位置加载时可能会遇到问题,但它可能会起作用。只要有provide方法或者可以调用的东西就可以了。

TL;DR - 我建议使用 browserify 或 require-kiss。


更新:

1:require-kiss现已死亡,作者已将其删除。从那时起我就一直使用 RequireJS 没有任何问题。 require-kiss 的作者写了 pakmanagerpakman。完全披露,我与开发商合作。

我个人更喜欢 RequireJS。它更容易调试(您可以在开发中拥有单独的文件,在生产中拥有单个部署的文件)并且构建在可靠的“标准”之上。

Check out ender. It does a lot of this.

Also, browserify is pretty good. I've used require-kiss¹ and it works. There are probably others.

I'm not sure about RequireJS. It's just not the same as node's. You may run into problems with loading from other locations, but it might work. As long as there's a provide method or something that can be called.

TL;DR- I'd recommend browserify or require-kiss.


Update:

1: require-kiss is now dead, and the author has removed it. I've since been using RequireJS without problems. The author of require-kiss wrote pakmanager and pakman. Full disclosure, I work with the developer.

Personally I like RequireJS better. It is much easier to debug (you can have separate files in development, and a single deployed file in production) and is built on a solid "standard".

辞慾 2024-12-05 13:34:28

我写了一个小脚本,允许异步和同步加载 Javascript 文件,这可能在这里有用。它没有依赖关系,并且与 Node.js 和 Node.js 兼容。 CommonJS。安装非常简单:

$ npm install --save @tarp/require

然后只需将以下行添加到 HTML 中即可加载主模块:

<script src="/node_modules/@tarp/require/require.min.js"></script>
<script>Tarp.require({main: "./scripts/main"});</script>

在主模块(当然还有任何子模块)中,您可以使用 require()正如您从 CommonJS/NodeJS 中知道的那样。完整的文档和代码可以在 GitHub 上找到。

I wrote a small script which allows asynchronous and synchronous loading of Javascript files, which might be of some use here. It has no dependencies and is compatible to Node.js & CommonJS. The installation is pretty easy:

$ npm install --save @tarp/require

Then just add the following lines to your HTML to load the main-module:

<script src="/node_modules/@tarp/require/require.min.js"></script>
<script>Tarp.require({main: "./scripts/main"});</script>

Inside your main-module (and any sub-module, of course) you can use require() as you know it from CommonJS/NodeJS. The complete docs and the code can be found on GitHub.

幸福%小乖 2024-12-05 13:34:28

Ilya Kharlamov 很棒的答案的变体,其中包含一些代码,使其可以与 Chrome 开发人员工具完美配合。

//
///- REQUIRE FN
// equivalent to require from node.js
function require(url){
    if (url.toLowerCase().substr(-3)!=='.js') url+='.js'; // to allow loading without js suffix;
    if (!require.cache) require.cache=[]; //init cache
    var exports=require.cache[url]; //get from cache
    if (!exports) { //not cached
            try {
                exports={};
                var X=new XMLHttpRequest();
                X.open("GET", url, 0); // sync
                X.send();
                if (X.status && X.status !== 200)  throw new Error(X.statusText);
                var source = X.responseText;
                // fix (if saved form for Chrome Dev Tools)
                if (source.substr(0,10)==="(function("){ 
                    var moduleStart = source.indexOf('{');
                    var moduleEnd = source.lastIndexOf('})');
                    var CDTcomment = source.indexOf('//@ ');
                    if (CDTcomment>-1 && CDTcomment<moduleStart+6) moduleStart = source.indexOf('\n',CDTcomment);
                    source = source.slice(moduleStart+1,moduleEnd-1); 
                } 
                // fix, add comment to show source on Chrome Dev Tools
                source="//@ sourceURL="+window.location.origin+url+"\n" + source;
                //------
                var module = { id: url, uri: url, exports:exports }; //according to node.js modules 
                var anonFn = new Function("require", "exports", "module", source); //create a Fn with module code, and 3 params: require, exports & module
                anonFn(require, exports, module); // call the Fn, Execute the module
                require.cache[url]  = exports = module.exports; //cache obj exported by module
            } catch (err) {
                throw new Error("Error loading module "+url+": "+err);
            }
    }
    return exports; //require returns object exported by module
}
///- END REQUIRE FN

A variation of Ilya Kharlamov great answer, with some code to make it play nice with chrome developer tools.

//
///- REQUIRE FN
// equivalent to require from node.js
function require(url){
    if (url.toLowerCase().substr(-3)!=='.js') url+='.js'; // to allow loading without js suffix;
    if (!require.cache) require.cache=[]; //init cache
    var exports=require.cache[url]; //get from cache
    if (!exports) { //not cached
            try {
                exports={};
                var X=new XMLHttpRequest();
                X.open("GET", url, 0); // sync
                X.send();
                if (X.status && X.status !== 200)  throw new Error(X.statusText);
                var source = X.responseText;
                // fix (if saved form for Chrome Dev Tools)
                if (source.substr(0,10)==="(function("){ 
                    var moduleStart = source.indexOf('{');
                    var moduleEnd = source.lastIndexOf('})');
                    var CDTcomment = source.indexOf('//@ ');
                    if (CDTcomment>-1 && CDTcomment<moduleStart+6) moduleStart = source.indexOf('\n',CDTcomment);
                    source = source.slice(moduleStart+1,moduleEnd-1); 
                } 
                // fix, add comment to show source on Chrome Dev Tools
                source="//@ sourceURL="+window.location.origin+url+"\n" + source;
                //------
                var module = { id: url, uri: url, exports:exports }; //according to node.js modules 
                var anonFn = new Function("require", "exports", "module", source); //create a Fn with module code, and 3 params: require, exports & module
                anonFn(require, exports, module); // call the Fn, Execute the module
                require.cache[url]  = exports = module.exports; //cache obj exported by module
            } catch (err) {
                throw new Error("Error loading module "+url+": "+err);
            }
    }
    return exports; //require returns object exported by module
}
///- END REQUIRE FN
心病无药医 2024-12-05 13:34:28
(function () {
    // c is cache, the rest are the constants
    var c = {},s="status",t="Text",e="exports",E="Error",r="require",m="module",S=" ",w=window;
    w[r]=function R(url) {
        url+=/.js$/i.test(url) ? "" : ".js";// to allow loading without js suffix;
        var X=new XMLHttpRequest(),module = { id: url, uri: url }; //according to the modules 1.1 standard
        if (!c[url])
            try {
                X.open("GET", url, 0); // sync
                X.send();
                if (X[s] && X[s] != 200) 
                    throw X[s+t];
                Function(r, e, m, X['response'+t])(R, c[url]={}, module); // Execute the module
                module[e] && (c[url]=module[e]);
            } catch (x) {
                throw w[E](E+" in "+r+": Can't load "+m+S+url+":"+S+x);
            }
        return c[url];
    }
})();

由于阻塞,最好不要在生产中使用。 (在 Node.js 中,require() 是一个阻塞调用,这很好)。

(function () {
    // c is cache, the rest are the constants
    var c = {},s="status",t="Text",e="exports",E="Error",r="require",m="module",S=" ",w=window;
    w[r]=function R(url) {
        url+=/.js$/i.test(url) ? "" : ".js";// to allow loading without js suffix;
        var X=new XMLHttpRequest(),module = { id: url, uri: url }; //according to the modules 1.1 standard
        if (!c[url])
            try {
                X.open("GET", url, 0); // sync
                X.send();
                if (X[s] && X[s] != 200) 
                    throw X[s+t];
                Function(r, e, m, X['response'+t])(R, c[url]={}, module); // Execute the module
                module[e] && (c[url]=module[e]);
            } catch (x) {
                throw w[E](E+" in "+r+": Can't load "+m+S+url+":"+S+x);
            }
        return c[url];
    }
})();

Better not to be used in production because of the blocking. (In node.js, require() is a blocking call is well).

醉梦枕江山 2024-12-05 13:34:28

Require-stub — 在浏览器中提供符合节点要求的 require,同时解决这两个问题模块和相对路径。使用类似于 TKRequire (XMLHttpRequest) 的技术。
生成的代码是完全可浏览器化的,因为 require-stub 可以替代 watchify

Require-stub — provides node-compliant require in browser, resolves both modules and relative paths. Uses technic similar to TKRequire (XMLHttpRequest).
Resulting code is fully browserifyable, in that require-stub can serve as a replacement for watchify.

幻梦 2024-12-05 13:34:28

Webmake 将 Node 风格的模块捆绑到浏览器中,尝试一下。

Webmake bundles Node-style modules to Browser, give it a try.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文