简体   繁体   中英

Importing via script tag vs importing via webpack

I installed the mux library using npm and import it like this

 <script defer src="../node_modules/mux.js/dist/mux.js"></script>

I know that this defines some global JS variables when this script is loaded. Are scripts that are loaded this way just a bunch of var definitions? Are they at all compatible with ES6 imports / webpack?

Is it possible to use webpack to bundle the script instead?

Yes.

You can use ProvidePlugin : Automatically load modules instead of having to import or require them everywhere.

plugins: [
    new webpack.ProvidePlugin({
       muxjs: 'mux.js/dist/mux.js', // By default, module resolution path is current folder (./**) and node_modules
    })
]

now simply use it in your modules(files):

const tools = muxjs.mp4.tools;

Whenever muxjs is encountered as free variable in a module, the 'mux.js/dist/mux.js' is loaded automatically and the muxjs variable is filled with the exports of the loaded module (or property in order to support named exports).

Webpack of course has a cache so this 3rd party library will only be downloaded once (unless you are working with multiple entries that load this 3rd party library).

Actually you can do ES6 import for mux.js like this:

import muxjs from "mux.js";

It will be available to use eg

const transmuxer = new muxjs.mp4.Transmuxer();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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